package com.liangtian.mdm.dm.jsp.service.imp;

// import com.liangtian.mdm.activiti.api.WorkFlowService;
// import com.liangtian.mdm.activiti.api.constant.CustomConst;
// import com.liangtian.mdm.activiti.api.dao.RunRecordDao;
// import com.liangtian.mdm.activiti.api.entity.RunRecord;
// import com.liangtian.mdm.activiti.api.entity.ShForm;
// import com.liangtian.mdm.activiti.api.entity.TjForm;
// import com.liangtian.mdm.activiti.busi2proc.dao.BusinessProcdefDao;
// import com.liangtian.mdm.activiti.busi2proc.model.BusinessProcdef;
// import com.liangtian.mdm.activiti.busi2proc.service.BusinessProcdefService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.checkRule.dao.CheckRuleDao;
import com.liangtian.mdm.dm.checkRule.model.CheckRule;
import com.liangtian.mdm.dm.common.constant.TableConst;
import com.liangtian.mdm.dm.common.enums.Flag;
import org.apache.commons.lang3.StringUtils;
import com.liangtian.mdm.dm.config.dao.AttrConfigDao;
import com.liangtian.mdm.dm.config.model.AttrConfig;
import com.liangtian.mdm.dm.group.dao.AttrGroupDao;
import com.liangtian.mdm.dm.group.dao.DataViewFlowDao;
import com.liangtian.mdm.dm.group.model.AttrGroup;
import com.liangtian.mdm.dm.group.model.DataViewFlow;
import com.liangtian.mdm.dm.jsp.common.ExcelUtil;
import com.liangtian.mdm.dm.jsp.common.JspUtil;
import com.liangtian.mdm.dm.jsp.dao.GenJspDao;
import com.liangtian.mdm.dm.jsp.dao.JspActionDao;
import com.liangtian.mdm.dm.jsp.model.GenSelect;
import com.liangtian.mdm.dm.jsp.service.AutoCodeService;
import com.liangtian.mdm.dm.jsp.service.JspActionService;
import com.liangtian.mdm.dm.jsp.util.SqlUtil;
import com.liangtian.mdm.dm.jsp.util.WFparamUtil;
import com.liangtian.mdm.dm.listener.CacheUtil;
import com.liangtian.mdm.dm.model.dao.ModelDao;
import com.liangtian.mdm.dm.model.model.Model;
import com.liangtian.mdm.dm.sql.factory.SystemAttributeFactory;
import com.liangtian.mdm.system.file.dao.SysFileDao;
import com.liangtian.mdm.system.file.model.SysFile;
import com.liangtian.mdm.system.parameter.service.SysParameterService;
import com.liangtian.mdm.system.user.dao.SysUserDao;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import com.liangtian.mdm.util.ExportUtil;
import com.liangtian.mdm.util.StringUtil;
// import org.activiti.engine.TaskService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings({"rawtypes", "unchecked"})
@Service
public class JspActionServiceImpl implements JspActionService {
    //注入用户dao层接口
    @Autowired
    SysUserDao sysUserDao;

    @Autowired
    private WFparamUtil wFparamUtil;
    @Autowired
    private JspActionDao jspActionDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrConfigDao attrConfigDao;

    @Autowired
    private GenJspDao genJspDao;

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private SqlUtil sqlUtil;

    @Autowired
    private ModelDao modelDao;

    @Autowired
    private DataViewFlowDao viewDao;

    // @Autowired
    // BusinessProcdefDao businessProcdefDao;
    // @Autowired
    // private BusinessProcdefService businessProcdefService;

    // @Autowired
    // private WorkFlowService workFlowService;
    // @Autowired
    // private TaskService taskService;
    // @Autowired
    // private RunRecordDao runRecordDao;
    //	@Autowired
//	private SysBusinessDao sysBusinessDao;
    @Autowired
    private SysFileDao sysFileDao;
    @Autowired
    CheckRuleDao checkRuleDao;
    @Autowired
    private AutoCodeService autoCodeService;
    @Autowired
    private SysParameterService sysParameterService;

    /**
     * 查询分页
     */
    @Override
    public PageInfo queryList(Map<String, Object> param) {

        PageInfo<List<Map>> pageInfo = null;
        try {
            Object mid = param.get("modelId");
            //模型ID
            String modelId = mid == null ? param.get("tableName").toString().substring(2) : mid.toString();
            //获取当前操作模型
            Model model = cacheUtil.getModel(modelId);
            //系统列
            StringBuilder sysCols = SystemAttributeFactory.getSystemColumnsBuilder();
            //业务属性
            //String busiCols = cacheUtil.getColumns(modelId);
            String busiCols = cacheUtil.getQueryColumns(modelId);
            String cols = sysCols.append(busiCols).toString();
            param.put("columns", cols.subSequence(0, cols.length() - 1));

            // 业务属性
            StringBuilder where = new StringBuilder();

            StringBuilder whereStarWith = new StringBuilder();
            //StringBuilder flowColumn = new StringBuilder();
            Map<String, AttrConfig> ma = cacheUtil.getAttrMap(modelId);
            //获取实时的AttrConfig 不从缓存拿数据
            Map<String, AttrConfig> map = this.getNewAttrConfig(modelId);

            // ///////////////////////////////////////////////////////////////////////////////
            // 业务场景：A表关联B表一个字段，现在想查询B表的其他字段，下面的做法是写个视图，查询字段A.*+B表想要显示的字段
            // 然后在js中指定modelId:A;tableName：视图名字。
            // 下面方法中会将关联的B表字段赋值到查询列中
            // 注意：在新建的视图中，关联显示的字段如果不作为查询条件，名称可自定义，如果需要作为查询条件，则用"c_"开头+数字，例如：c_999，
            // 用数字是因为在spring-mybatis.xml文件中有定义"<plugin interceptor="com.liangtian.mdm.base.filter.CameHumpInterceptor"></plugin>"，下划线被去掉并转为驼峰写法，不符合下面代码中拼接查询条件的写法;

            List<Map<String, Object>> columnsList = new ArrayList<Map<String, Object>>();
            if ("V_".equals(param.get("tableName").toString().substring(0, 2).toUpperCase())) {
                columnsList = this.queryAlltabcolumns(param.get("tableName").toString());
                // 将视图中关联的字段加入查询字段中
                cols = this.addColumns(columnsList, cols);
                param.put("columns", cols.subSequence(0, cols.length() - 1));
                // ma = this.addma(ma,
                // sysCols.toString(),columnsList);//此方法会将视图中多加的字段加入ma,放入缓存，影响该模型其他地方的操作，比如新增
                map = this.addmap(map, sysCols.toString(), columnsList);
            }
            // ///////////////////////////////////////////////////////////////////////////////
            for (String key : param.keySet()) {
                if (key.startsWith(TableConst.COLUMNPREFIX.toLowerCase())) {
                    AttrConfig ac = new AttrConfig();
                    if ("V_".equals(param.get("tableName").toString().substring(0, 2).toUpperCase())) {
                        ac = map.get(key.toUpperCase());
                    } else {
                        ac = ma.get(key.toUpperCase());
                    }
                    if (ac != null) {
                        AttrConfig config = map.get(key.toUpperCase());
                        if ("1".equals(config.getIsSeniorQuery()) && param.get(key).toString().indexOf(";") != -1) {
                            where.append(this.analysisGjQuery(param, config, key));
                        } else {
                            //如果这个属性列设置的是复选框
                            if ("checkBoxType".equals(ac.getAttrType())) {
                                String dsTable = ac.getDataSourceTable().trim();
                                if (dsTable != null && !dsTable.isEmpty()) {
                                    Model modelds = cacheUtil.getModel(dsTable);
                                    Map<String, String> cond = new HashMap<String, String>();
                                    cond.put("caseColumn", "");
                                    cond.put("sourceTable", modelds.getTableName());
                                    cond.put("sourceCol", ac.getDataSourceShowColumn());
                                    String ModuleType = ac.getModuleType();
                                    //判断复选框的模型中间是否有逗号隔开（即复选框是否选择了多个值）
                                    if (param.get(key).toString().indexOf(",") != -1) {//包含逗号
                                        String co3o = "";
                                        for (String str : param.get(key).toString().split(",")) {//一个个的去解析这个值
                                            String Id = getdsTableIdbyColum(cond, ModuleType).get(str);
                                            if (!StringUtils.isEmpty(Id)) {
                                                co3o = co3o + Id.toString() + ",";
                                            }
                                        }
                                        String string = co3o.substring(0, co3o.length() - 1);
                                        where.append(" and ").append("t." + key).append(" = '").append(string.trim()).append("' ");
                                    } else {
                                        String Id = getdsTableIdbyColum(cond, ModuleType).get(param.get(key).toString());
                                        if (!StringUtils.isEmpty(Id)) {
                                            where.append(" and ").append("t." + key).append(" ='").append(Id.toString()).append("' ");
                                        }
                                    }
                                }
                            } else if ("popList".equals(ac.getAttrType()) || "radioType".equals(ac.getAttrType())
                                    || "selectList".equals(ac.getAttrType()) || "listTree".equals(ac.getAttrType())) {
//									if("1".equals(ac.getModuleType())){//本模型是下拉或弹出的关联设置
//										where.append(" and ").append(key).append(" = #{").append(key).append("} ");
//									}else
                                if ("5".equals(ac.getModuleType())) {//外部数据选择
                                    where.append(" and ").append(key).append(" like '%'||#{").append(key).append("}||'%' ");
                                } else {
                                    //列表查询的是id，但是前台传递过来的是名称
                                    String dsTable = ac.getDataSourceTable();
                                    String columnV = ac.getDataSourceShowColumn();
                                    if (null != dsTable && !"".equals(dsTable)) {
                                        Map treeMap = new HashMap();
                                        treeMap.put("columns", "t.ID");
                                        treeMap.put("tableName", "T_" + dsTable);
                                        treeMap.put("where", "t." + columnV + "='" + param.get(key).toString() + "' and t.state = 4 ");
                                        List<Map<String, Object>> datLst = jspActionDao.queryList(treeMap);
                                        if (datLst.size() > 0) {
                                            Map<String, Object> dataMap = datLst.get(0);
                                            String idValue = (String) dataMap.get("id");
                                            if (!StringUtils.isEmpty(idValue)) {
                                                where.append(" and ").append("t." + key).append(" ='").append(idValue).append("' ");
                                            }
                                        }
                                    }
                                }
                            } else {
                                where.append(" and ").append(key).append(" like '%'||#{").append(key).append("}||'%' ");
                            }
                        }
                    }
                }
                if (key.startsWith(TableConst.COLUMNPREFIX)) {
                    if ("1".equals(model.getClassType())) {//父子树
                        whereStarWith.append(" start with t." + key).append(" = ").append("'" + param.get(key).toString() + "'");
                        whereStarWith.append(" connect by  prior t.id = t." + key);
                    } else if ("2".equals(model.getClassType())) {//分类树
                        //本模型的所有属性列
                        List<AttrConfig> amLst = cacheUtil.getAttrList(modelId);
                        for (AttrConfig ac : amLst) {
                            if (ac.getClassColumn().equals("1")) {//是否作为关联属性
                                String aTable = ac.getDataSourceTable();//关联的表名
                                String aColumn = ac.getTreeViewColumn();//关联的列
                                if (param.get(key).toString() != null) {
                                    whereStarWith.append(" and t." + key).append(" in ");
                                    whereStarWith.append("(select id  from T_" + aTable + " m  "
                                            + " where 1=1 "
                                            + " and m.state ='4'"
                                            + " and m.status =0 "
                                            + " start with m." + aColumn + " = '" + param.get(key).toString() + "' "
                                            + " connect by prior m.id = m." + aColumn + " "
                                            + " union  select  '" + param.get(key).toString() + "'  id from dual )");
                                }
                            }
                        }
                    }
                }
            }
            param.put("where", where);
            param.put("whereStarWith", whereStarWith);
            StringBuilder sort = new StringBuilder();
            List<AttrConfig> acList = cacheUtil.getAttrList(modelId);
            for (AttrConfig ac : acList) {
                if (ac.getIsOrder() != null && ac.getIsOrder() == 1) {
                    sort.append(", ").append(ac.getAttrColumn());
                    if (ac.getOrderRule() != null && ac.getOrderRule() == 1) {
                        sort.append(" asc");
                    } else if (ac.getOrderRule() != null && ac.getOrderRule() == 2) {
                        sort.append(" desc");
                    }
                }
            }
            sort.append(", to_number(id)  desc ").append(", ").append(" to_number(version) ").append("  asc");
//			sort.append(", to_number(id)  desc ").append(", ").append(" to_number(version) ").append("  desc");
//			sort.append(", to_number(id)  asc ").append(", ").append(" to_number(version) ").append("  asc");
//
            param.put("orderBy", sort.substring(1));

            // 当前用户参与审核数据查询条件
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            //默认查询条件
            String operType = String.valueOf(param.get("operType"));


            if ("apply".equals(operType) || ("update".equals(operType) && param.get("tableName").toString().contains("_UPDATE"))) {
                param.put("createrId", user.getUserId());
            }
            param.put("operType", operType);

            Object pNo = param.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());//页码
            } else {
                pageNum = 1;
            }
            //pageSize=0时不分页
            pageSize = Integer.parseInt(param.get("limit").toString());//每页条数
            PageHelper.startPage(pageNum, pageSize);//分页  注释掉后就不会进行分页
            List<Map<String, Object>> list = null;
            if (Flag.OPER_2.getCode().equals(operType)) {
                // 变更表
                param.put("modifyTableName", param.get("tableName") + TableConst.MODIFYSUFFIX);
                //Model model = cacheUtil.getModel(modelId);
                if (model.getIsSubtable() == 1) {
                    //从表没有流程相关数据
                    String subTab = param.get("tableName").toString();
                    if (subTab.endsWith(TableConst.MODIFYSUFFIX)) {
                        param.put("modifyTableName", param.get("tableName"));
                        param.put("bgstate", param.get("bgstate"));
                        param.put("zbstate", param.get("zbstate"));
                    } else {
                        param.put("modifyTableName", param.get("tableName") + TableConst.MODIFYSUFFIX);
                        param.put("bgstate", param.get("bgstate"));
                        param.put("zbstate", param.get("zbstate"));
                    }
                    list = jspActionDao.querySubTableList(param);
                } else {
                    param.put("approveUserId", String.valueOf(user.getUserId()));
                    list = jspActionDao.queryApproveList(param);
                }
            } else if (Flag.OPER_1.getCode().equals(operType) && !Flag.FORQUERY.getCode().equals(param.get(Flag.FORQUERY.getColumn()))) {
                list = jspActionDao.queryUpdateList(param);
            } else {
                list = jspActionDao.queryList(param);
            }

            pageInfo = new PageInfo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    /**
     * 删除
     */
    @Override
    public int delete(Map<String, Object> param) {
        // 主表
        String tableName = String.valueOf(param.get("tableName"));
        int ret = jspActionDao.deleteByPk(param);
        List<Model> subModels = modelDao.isHasSub(tableName.split("_")[1]);
        if (!subModels.isEmpty()) {
            for (Model sub : subModels) {
                String table = sub.getTableName();
                //变更主表【对应】变更从表
                if (tableName.endsWith(TableConst.MODIFYSUFFIX)) {
                    table = table + TableConst.MODIFYSUFFIX;
                }
                Map<String, Object> subParam = genSubProcessParam(table, param.get("ids").toString());
                if (subParam != null) {
                    this.delete(subParam);
                }
            }
        }
        //删除数据的时候，判断一下这个模型是不是多视图模型，还有是不是申请页面删除操作

        if (!tableName.endsWith(TableConst.MODIFYSUFFIX)) {//判断表的结尾是否含有“_UPDATE”
            Model model = cacheUtil.getModel(tableName.split("_")[1]);
            if (model.getIsMoreView() == 1) {//是多视图数据
                String ids = param.get("ids").toString();
                String[] idLst = ids.split(",");
                for (int i = 0; i < idLst.length; i++) {
                    Map map = new HashMap();
                    map.put("modelId", tableName.split("_")[1]);
                    map.put("dataId", idLst[i]);
                    this.deleteDataFlow(map);
                }
            }
        }
        return ret;
    }

    /**
     * 组装递归的参数
     *
     * @param tableName 表名
     * @param idStrs    以逗号分隔的ID串
     * @return
     */
    private Map<String, Object> genSubProcessParam(String tableName, String idStrs) {
        String[] idsLst = idStrs.split(",");
        Map<String, Object> result_map = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        result_map.put("tableName", tableName);
        result_map.put("idLst", idsLst);
        result_map.put("idType", "MAINID");
        List<String> resLst = jspActionDao.selectSubDataIdList(result_map);
        if (resLst.isEmpty()) {
            return null;
        } else {
            for (int j = 0; j < resLst.size(); j++) {
                sb.append(resLst.get(j)).append(",");
            }
            result_map.put("ids", sb.substring(0, sb.length() - 1));
            return result_map;
        }
    }

    @Override
    public int check(Map<String, Object> map) {
        String sql = "update " + map.get("tableName").toString()
                + " set state = " + Flag.STATE_1.getCode()
                + " where id in (" + map.get("ids") + ") ";
        boolean ret = jdbcDao.executeSql(sql);
        int r = 0;
        if (ret) {
            r = 1;
        }
        return r;
    }

    /**
     * 新增申请
     */
    @Override
    public Map<String, Object> insert(Map<String, Object> param) {
        Map<String, Object> insertMap = new HashMap<>();
        Map<String, Object> resMap = sqlUtil.genInsertSql(param);
        boolean flag = jdbcDao.executeSql((String) resMap.get("sql"));
        insertMap.put("idValue", resMap.get("idValue"));
        insertMap.put("flag", flag);
        insertMap.put("fileList", resMap.get("fileList"));
        return insertMap;
    }

    /**
     * 新增申请 (中纺SRM接口用)
     *
     * @param param
     * @return
     * @author jiangyh
     * @date 2017-09-25
     */
    @Override
    public Map<String, Object> insert_zf(Map<String, Object> param, SysUser user) {
        Map<String, Object> insertMap = new HashMap<>();
        Map<String, Object> resMap = sqlUtil.genInsertSql_zf(param, user);
        boolean flag = jdbcDao.executeSql((String) resMap.get("sql"));
        insertMap.put("idValue", resMap.get("idValue"));
        insertMap.put("flag", flag);
        insertMap.put("fileList", resMap.get("fileList"));
        return insertMap;
    }

    /**
     * 变更、冻结、解冻
     */
    @SuppressWarnings("serial")
    @Override
    public boolean insertBg(Map<String, Object> param) {
        List<String> sqls = new ArrayList<String>();
        final String tableName = param.get("tableName").toString();
        //查询从表
        List<Model> subModels = modelDao.isHasSub(tableName.split("_")[1]);

        if (!subModels.isEmpty()) {
            Map<String, String> m = new HashMap<String, String>() {
                {
                    put("tableSeqNextval", tableName + TableConst.SEQUENCESUFFIX + ".nextVal");
                }
            };
            String[] ids = param.get("ids").toString().split(",");
            for (String id : ids) {
                String bgId = jspActionDao.selectIdBySeq(m);
                param.put("bgId", bgId);
                param.put("ids", id);
                sqls = sqlUtil.genBgInsertSql(param, sqls);//主表
                ///刘晶-往从表分发数据,目前
                for (Model sub : subModels) {
                    Map<String, Object> subParam = genSubProcessParam(sub.getTableName(), id);
                    if (subParam != null) {
                        //递归调用
                        subParam.put("operType", param.get("operType"));
                        subParam.put("modelId", sub.getId());
                        subParam.put("tableName", sub.getTableName() + TableConst.MODIFYSUFFIX);
                        subParam.put("mainDataId", bgId); //从表保存变更数据主键
                        //从表这块，逻辑需要改一改
                        sqls = sqlUtil.genSubBgInsertSql(subParam, sqls);
//						sqls = sqlUtil.genBgInsertSql(subParam,sqls);
                    }
                }
            }
        } else {
            //生成插入sql
            sqls = sqlUtil.genBgInsertSql(param, sqls);
        }
        boolean ret = jdbcDao.executeSqlList(sqls, true);
        return ret;
    }

    /**
     * 冻结、解冻
     */
    @Override
    public boolean changeStatus(Map<String, Object> param) {
        // 主表
        String tableName = String.valueOf(param.get("tableName"));
        List<String> sqls = new ArrayList<String>();
        sqls.add(sqlUtil.genStatusUpdateSql(param));
        //查询从表
        List<Model> subModels = modelDao.isHasSub(param.get("tableName").toString().split("_")[1]);
        if (!subModels.isEmpty()) {
            for (Model sub : subModels) {
                String table = sub.getTableName();
                //变更主表【对应】变更从表
                if (tableName.endsWith(TableConst.MODIFYSUFFIX)) {
                    table = table + TableConst.MODIFYSUFFIX;
                }
                Map<String, Object> subParam = genSubProcessParam(table, param.get("ids").toString());
                if (subParam != null)
                    //递归调用
                {
                    sqls.add(sqlUtil.genStatusUpdateSql(subParam));
                }
            }
        }
        return jdbcDao.executeSqlList(sqls, true);
    }

    /**
     * 编辑更新
     */
    @Override
    public boolean update(Map<String, Object> param) {
        String sql = sqlUtil.genUpdateSql(param);
        return jdbcDao.executeSql(sql);
    }

    /**
     * 查询单条记录
     */
    @Override
    public Map<String, Object> queryOne(Map<String, Object> map) {
        Map<String, Object> result_map = new HashMap<>();
        result_map = jspActionDao.queryOne(map);
        String modelId = (String) map.get("modelId");
        List<AttrConfig> acLst = cacheUtil.getAttrList(modelId);
        for (AttrConfig attrConfig : acLst) {
            if (attrConfig.getAttrType() != null && "BLOB".equals(attrConfig.getAttrType())) {
                String column = attrConfig.getAttrColumn().toLowerCase();
                Map<String, Object> cond = new HashMap<>();
                cond.put("dataId", map.get("id"));
                cond.put("surveyType", modelId);
                cond.put("operType", map.get("operType"));
                cond.put("fileColumn", column);
                List<SysFile> sysFileLst = sysFileDao.queryFileBySurvey(cond);
                if (!sysFileLst.isEmpty()) {
                    result_map.put(column, sysFileLst);
                }
            }
        }
        return result_map;
    }

    /**
     * 查询单条记录
     * 复杂组件实际值的转义
     */
    @Override
    public Map<String, Object> queryDetail(Map<String, Object> map) {
        Map<String, Object> result_map = new HashMap<>();
        String columns = cacheUtil.getQueryColumns(map.get("tableName").toString().split("_")[1]);
        map.put("columns", columns.substring(0, columns.length() - 1));
        result_map = jspActionDao.queryDetail(map);

        String modelId = map.get("tableName").toString().split("_")[1];
        Map<String, Object> cond = new HashMap<>();
        cond.put("dataId", map.get("id"));
        cond.put("surveyType", modelId);

        String operType = (String) map.get("operType");
        //审核
        if (Flag.OPER_2.getCode().equals(operType)) {
            cond.put("operType", Flag.OPER_100.getCode());
        } else if (Flag.OPER_1.getCode().equals(operType)  //变更
                || Flag.OPER_3.getCode().equals(operType))//冻结
        {
            cond.put("operType", Flag.OPER_1.getCode());
        } else if (Flag.OPER_4.getCode().equals(operType))//解冻
        {
            cond.put("operType", Flag.OPER_4.getCode());
        } else if (Flag.OPER_100.getCode().equals(operType))//申请
        {
            cond.put("operType", "apply");
        }

        List<AttrConfig> acLst = cacheUtil.getAttrList(modelId);
        for (AttrConfig attrConfig : acLst) {
            if (attrConfig.getAttrType() != null && "BLOB".equals(attrConfig.getAttrType())) {
                String column = attrConfig.getAttrColumn().toLowerCase();
                cond.put("fileColumn", column);
                List<SysFile> sysFileLst = sysFileDao.queryFileBySurvey(cond);
                if (!sysFileLst.isEmpty()) {
                    result_map.put("fileSize", sysFileLst.size());
                    if (sysFileLst.size() == 1) {
                        result_map.put(column, sysFileLst.get(0).getFileName());
                    } else {
                        result_map.put(column, sysFileLst.get(0).getFileName() + "等共" + sysFileLst.size() + "个附件");
                    }
                }
            }
        }
        return result_map;
    }

    /**
     * 数据提交  <br/>
     * 已被 submitFlow 替代
     */
    @Override
    @Deprecated
    public boolean submit(Map<String, Object> param) {
        // 主表
        String tableName = String.valueOf(param.get("tableName"));
        List<String> sqls = sqlUtil.genSubmitSql(param);
        //判断是否有从表
        List<Model> subModels = modelDao.isHasSub(tableName.split("_")[1]);
        if (!subModels.isEmpty()) {
            for (Model sub : subModels) {
                String table = sub.getTableName();
                //变更主表【对应】变更从表
                if (tableName.endsWith(TableConst.MODIFYSUFFIX)) {
                    table = table + TableConst.MODIFYSUFFIX;
                }
                Map<String, Object> subParam = genSubProcessParam(table, param.get("ids").toString());
                if (subParam != null) {
                    sqls.addAll(sqlUtil.genSubmitSql(subParam));
                }
            }
        }
        //提交
        boolean flag = jdbcDao.executeSqlList(sqls, true);
        return flag;
    }

    // private boolean checkAttrOnly(TjForm form) {
    //     boolean flag = true;
    //     String errorText = "";
    //     int countCheck = 0;
    //     List<String> sqls = new ArrayList<String>();
    //     Map<String, Object> map = new HashMap<>();
    //     String dataId = form.getDataId();
    //     String tableName = form.getTableName();
    //     String modelId = form.getTableName().split("_")[1];
    //     String modelType = cacheUtil.getModel(modelId).getModelType();
    //     SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
    //     map.put("user_id", user.getUserId());
    //     map.put("id", dataId);
    //     map.put("tableName", "T_" + modelId);
    //     String checkParams = form.getCheckParams();//获取唯一标识列有几个
    //     String checkOper = String.valueOf(Flag.toValue(form.getOperType(), "opertype"));
    //     map.put("opertype", checkOper);
    //     if ((checkParams != null && !"".equals(checkParams.trim())) && (checkOper.equals("submit") || checkOper.equals("update"))) {
    //         //在此处添加是否走定制性校验唯一方法（刘晶添加此处）
    //         //if(checkParams.contains("&")){//此处表示,唯一性校验的参数中含有&符号，表示需要走定制性校验方法
    //         if (checkParams.contains(ConstantBean.REPLACE_AD_FH)) {//对于特殊字符，这样处理 REPLACE_AD_FH ="*_*";//替换“&”符号
    //             String params[] = checkParams.split(":");//根据：获取哪几个列合并作为唯一标识
    //             //获取唯哪几个列作为唯一标识 eg:（c_001,c_007）表示c_001和c_007这两列作为唯一标识
    //             String column = params[0];//c_001,c_007
    //             //获取列对应的值   eg: 80543843423&2
    //             String value = params[1];//data[i].c_001+"&"+data[i].c_007
    //             String[] col = column.split(",");
    //             //String[] val = value.split("&");//ConstantBean.REPLACE_AD_FH
    //             String[] val = value.split(ConstantBean.REPLACE_AD_FH);
    //             map.put("column1", col[0]);
    //             AttrConfig t1 = cacheUtil.getAttrConfig(modelId, col[0].toUpperCase().toString());
    //             //获取本属性列的属性设置信息 --1.判断本属性列是否引用关系()
    //             if (null != t1.getModuleType() && "1".equals(t1.getModuleType())) {//如果是关联关系
    //                 String ytab = "T_" + t1.getDataSourceTable();
    //                 String ycol = t1.getDataSourceShowColumn();
    //                 Map mapycol = new HashMap();
    //                 mapycol.put("columns", ycol + ",id");
    //                 mapycol.put("tableName", ytab);
    //                 mapycol.put("where", "t." + ycol + "='" + val[0] + "' ");  //and t.state = 4把这个条件去掉
    //                 List<Map<String, Object>> datLst = jspActionDao.queryList(mapycol);
    //                 if (datLst.size() > 0) {
    //                     Map<String, Object> dataMap = datLst.get(0);
    //                     String idValue = (String) dataMap.get("id");
    //                     if (idValue != null) {
    //                         val[0] = idValue;
    //                     }
    //                 }
    //                 map.put("value1", val[0]);
    //             } else {
    //                 map.put("value1", val[0]);
    //             }
    //
    //             map.put("column2", col[1]);
    //             AttrConfig t2 = cacheUtil.getAttrConfig(modelId, col[1].toUpperCase().toString());
    //             if (t2.getModuleType().equals("1")) {//如果是关联关系
    //                 String xtab = "T_" + t2.getDataSourceTable();
    //                 String xcol = t2.getDataSourceShowColumn();
    //                 Map mapxcol = new HashMap();
    //                 mapxcol.put("columns", xcol + ",id");
    //                 mapxcol.put("tableName", xtab);
    //                 mapxcol.put("where", "t." + xcol + "='" + val[1] + "' ");//and t.state = 4
    //                 List<Map<String, Object>> datLst = jspActionDao.queryList(mapxcol);
    //                 if (datLst.size() > 0) {
    //                     Map<String, Object> dataMap = datLst.get(0);
    //                     String idValue = (String) dataMap.get("id");
    //                     if (idValue != null) {
    //                         val[1] = idValue;
    //                     }
    //                 }
    //                 map.put("value2", val[1]);
    //             } else {
    //                 map.put("value2", val[1]);
    //             }
    //
    //             if ("0".equals(modelType)) { //主数据类型 定制化开发的东西，目前不考虑字典模型，只考虑主数据
    //                 countCheck = this.checkcolumnNameToWanDa(map);
    //             }
    //             if (countCheck > 0) {//如果数据>0
    //                 AttrConfig ac1 = cacheUtil.getAttrConfig(modelId, col[0].toUpperCase().toString());
    //                 AttrConfig ac2 = cacheUtil.getAttrConfig(modelId, col[1].toUpperCase().toString());
    //                 errorText = errorText + ac1.getAttrName() + "和" + ac2.getAttrName() + "作为唯一校验,校验唯一性数据已存在！;";
    //                 sqls.add("update " + tableName + " set state = 2,error_text = '" + errorText + "' where id = '" + dataId + "'");
    //             }
    //         } else {
    //             //String params[] = checkParams.split("@");//REPLACE_AT_FH ="@_@";//替换“@”符号
    //             String params[] = checkParams.split(ConstantBean.REPLACE_AT_FH);
    //
    //             for (int m = 0; m < params.length; m++) {
    //                 String param = params[m];//获取唯一标识列组1
    //                 String valusColumn[] = param.split(":");
    //                 String column = valusColumn[0];//列名
    //                 String value = valusColumn[1];//值
    //                 //针对万达定制型开发  判断校验唯一性的属性字段中，
    //                 //是否含有"&"符号，如果含有此符号，则表示是定制型唯一性校验
    //                 map.put("column", column);
    //                 map.put("value", value);
    //                 if ("0".equals(modelType)) { //主数据类型
    //                     countCheck = this.checkcolumnName(map);
    //                 } else { //字典类型
    //                     countCheck = jspActionDao.checkcolumnNameZd(map);
    //                 }
    //                 if (countCheck > 0) {//如果数据>0
    //                     AttrConfig ac = cacheUtil.getAttrConfig(modelId, column.toUpperCase().toString());
    //                     errorText = errorText + ac.getAttrName() + "的值【" + value + "】已存在;";
    //                     sqls.add("update " + tableName + " set state = 2,error_text = '" + errorText + "' where id = '" + dataId + "'");
    //                 }
    //             }
    //         }
    //     }
    //     if ("".equals(errorText)) {
    //         flag = true;
    //     } else {
    //         flag = false;
    //         jdbcDao.executeSqlList(sqls, true);
    //     }
    //     return flag;
    // }


    /**
     * 工作流提交
     */
    // @Override
//     public boolean submitFlow(List<TjForm> forms) {
//         //对应模型
//         String modelId = forms.get(0).getTableName().split("_")[1];
//         Model model = cacheUtil.getModel(modelId);
//         String isMoreView = model.getIsMoreView() + ""; //是否多视图
//         //判断是否有从表
//         List<Model> subModels = modelDao.isHasSub(modelId);
//         boolean needFlow = true;
//         boolean rsflag = false;
//         boolean jdbcflag = false;
//         //数据字典
//         if ("1".equals(model.getModelType())) {
//             needFlow = false;
//         } else {
//             if (0 == model.getIsWorkflow()) {
//                 needFlow = false;
//             }
//         }
//
//         //（当前批次提交）暂时缓存流程定义
//         Map<String, BusinessProcdef> pdMap = new HashMap<String, BusinessProcdef>();
//         //查询条件
//         Map<String, Object> cond = new HashMap<>();
//         SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
//         cond.put("orgId", user.getOrganizationId());
//
//         //数据更新sql集合
//         List<String> sqls = new ArrayList<String>();
//         StringBuilder wfSql = new StringBuilder();
//
//         for (TjForm form : forms) {
//             sqls = new ArrayList<String>();
//
//             Map<String, Object> vars;//流程流转参数
//             Map<String, Object> fromMap = new HashMap<>();
//             fromMap.put("id", form.getDataId());
//             fromMap.put("tableName", form.getTableName());
//             fromMap.put("type", "submit");
//             vars = wFparamUtil.formatWfParam(fromMap);
//
//             Map<String, Object> map = new HashMap<>();
//             Map<String, Object> mapOldData = new HashMap<>();
//
//             String dataId = form.getDataId();
//             String tableName = form.getTableName();
//             map.put("id", dataId);
//             map.put("tableName", "T_" + modelId);
//             //提交之前的校验方法，若是校验通过 flagOnly 为true,否则,为false
//             boolean flagOnly = this.checkAttrOnly(form);
//             if (flagOnly) {
//                 //主数据
//                 if (needFlow) {//表示走流程
//                     String orginTable = tableName;
//                     if (tableName.toUpperCase().endsWith(TableConst.MODIFYSUFFIX)) {
//                         orginTable = tableName.substring(0, tableName.lastIndexOf("_"));
//                     }
//                     cond.put("tableName", orginTable);  //业务类型
//                     String operType = String.valueOf(Flag.toValue(form.getOperType(), "opertype"));
//                     String key = operType; //操作类型
//                     String dataType = form.getDataType(); //数据类型
//                     if (!StringUtils.isBlank(dataType)) {
//                         key = key + "@" + dataType;
//                     }
//
//                     //业务关联流程设置
//                     BusinessProcdef bp = null;
//                     if ("0".equals(isMoreView)) { //不是多视图
//                         if (pdMap.containsKey(key)) {
//                             bp = pdMap.get(key);
//                         } else {
//                             cond.put("dataType", dataType);
//                             cond.put("operType", operType);
//
//                             bp = workFlowService.validate(cond); //流程定义
//                             pdMap.put(key, bp);
//                         }
//                     } else { //是多视图
//                         map.put("modelId", modelId);
//                         // edit by xiaoliu 在此处添加多视图，进行数据校验，如果是变更流程的话，需要对流程里面的dataId数据进行原始数据ID替换   2018-06-20 19:16
//                         if (operType.equals("update")) {
//                             //根据变更数据，查询数据的原始数据ID
//                             mapOldData.put("tableName", tableName);
//                             mapOldData.put("id", dataId);
//                             mapOldData.put("columns", "*");
//                             Map dataMap = jspActionDao.queryDetail(mapOldData);
//
//                             map.put("dataId", dataMap.get("originId").toString());
//                         } else {
//                             map.put("dataId", dataId);
//                         }
//
//                         //edit end
//                         map.put("operType", operType);
//                         //由于万达多视图那个流程问题报错，目前这块先隐藏掉  ---刘晶 2017-08-14 21:45 pm
//                         cond.put("views", viewDao.queryDataViewFlowsByDataId(map));
//                         cond.put("dataType", dataType);
//                         cond.put("operType", operType);
//
//                         bp = workFlowService.validate(cond); //流程定义
//                         pdMap.put(key, bp);
//                     }
//
//                     //主数据不需要流程
//                     if (bp == null) {
//                         needFlow = false;
//                     } else {
//                         //历史记录版本统一更新
//                         sqls.add("UPDATE WF_RUN_HISTORY SET REV = rev+1 where DATA_ID = '" + dataId + "' and BUSI_TABLE='" + tableName + "'");
//                         // 启动工作流
//                         ProcessInstance instance = workFlowService.startFlow(bp, vars);
//                         //				Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
//                         List<Task> taskLst = taskService.createTaskQuery().processInstanceId(instance.getId()).list();
//                         // 自动生成【送审】记录
//                         wfSql.append("INSERT INTO WF_RUN_HISTORY (RID, WF_ID, BUSI_ID, BUSI_NAME, BUSI_TABLE, OPER_TYPE, ")
//                                 .append(" INSTANCE_ID, TASK_ID, NODE_ID, ASSIGNEE, DEFINITION_ID, PASS, ")
//                                 .append(" OPER_DATE, DATA_ID, OPINION, APPROVE_DATE, APPROVE_USER, REV ) VALUES ( ")
//                                 .append("WF_RUN_HISTORY_SEQ.nextval, ").append(bp.getId()).append(", ").append(bp.getBusiId())
//                                 .append(", '").append(bp.getBusiName()).append("','").append(form.getTableName()).append("', '")
//                                 .append(operType).append("', null, null, null, null, '").append(bp.getProcdefId())
//                                 .append("', null, sysdate, '").append(dataId).append("', '送审', sysdate")
//                                 .append(", '").append(user.getUserId()).append("', 0 ) ");
//                         sqls.add(wfSql.toString());
//                         wfSql.delete(0, wfSql.length());
//
//
// 					/*
// 						String activitiId=null;
// 						if(instance.getActivityId()==null){
// 							activitiId=taskLst.get(0).getTaskDefinitionKey();
// 						}else{
// 							activitiId=instance.getActivityId();
// 						}
// 						List<SysUser> users= businessProcdefService.getTaskCandidateUsers(bp.getId(), activitiId);
// 						List<String> userLst = new ArrayList<>();
// 						for(SysUser u : users){
// 							userLst.add(u.getUserId().toString());
// 						}
// 						 */
//
//                         for (int i = 0; i < taskLst.size(); i++) {
//                             /**
//                              * 并行
//                              */
//                             List<SysUser> users = businessProcdefService.getTaskCandidateUsers(bp.getId(), taskLst.get(i).getTaskDefinitionKey());
//                             List<String> userLst = new ArrayList<>();
//                             for (SysUser u : users) {
//                                 userLst.add(u.getUserId().toString());
//                             }
//                             String assignee = "";
//                             /**
//                              * List<SysUser> users= businessProcdefService.getTaskCandidateUsers(bp.getId(), activitiId);获取的是某个task节点的审批审批人,
//                              if(taskLst.size()==1){
//                              assignee=StringUtil.join(userLst, "user(", ")");
//                              }else{
//                              assignee=StringUtil.join(userLst.get(i), "user(", ")");
//                              }
//                              为什么   assignee=StringUtil.join(userLst.get(i), "user(", ")");这么写???
//                              */
//                             assignee = StringUtil.join(userLst, "user(", ")");
//
//                             Task task = taskLst.get(i);
//                             wfSql.append("INSERT INTO WF_RUN_DATA (RID, WF_ID, BUSI_ID, BUSI_NAME, OPER_TYPE, INSTANCE_ID, TASK_ID, ")
//                                     .append(" NODE_ID, ASSIGNEE, OPER_DATE, BUSI_TABLE, DATA_ID, DEFINITION_ID, TASKSTATE) VALUES ( ")
//                                     .append(" WF_RUN_DATA_SEQ.nextval, ").append(bp.getId()).append(", ").append(bp.getBusiId()).append(", '")
//                                     .append(bp.getBusiName()).append("', '").append(operType).append("', ").append(task.getProcessInstanceId())
//                                     .append(", ").append(task.getId()).append(", '").append(task.getTaskDefinitionKey()).append("', '")
//                                     .append(assignee).append("', sysdate, '").append(form.getTableName()).append("', '").append(dataId)
//                                     .append("', '").append(bp.getProcdefId()).append("', 1 ) ");
//                             sqls.add(wfSql.toString());
//                             wfSql.delete(0, wfSql.length());
//                         }
//                     }
//                 } else {//表示不走流程
// //					String[] strArr = autoCodeService.autoCode(modelId,form.getDataId());//自动附码
// //					if(!StringUtils.isEmpty(strArr[1])){
// ////						String err = "自动附码失败:"+strArr[1];
// //						System.out.println("***自动附码失败***:"+strArr[1]);
// //					}
//
//                     if (tableName.endsWith(TableConst.MODIFYSUFFIX)) {//变更页面提交有三种操作，变更，冻结，解冻
//                         StringBuilder sb = new StringBuilder();
//                         String tab = tableName.substring(0, tableName.lastIndexOf("_"));
//                         if (!"变更".equals(form.getOperType())) {
//                             if ("冻结".equals(form.getOperType())) {//如果是冻结操作
//                                 sb.append("update " + tab + " set status = ");
//                                 sb.append(Flag.STATUS_1.getCode());
//                             } else if ("解冻".equals(form.getOperType())) {//如果是解冻操作
//                                 sb.append("update " + tab + " set status = ");
//                                 sb.append(Flag.STATUS_0.getCode());
//                             }
//                             Map<String, Object> mapAu = new HashMap<>();
//                             mapAu.put("tableName", tableName);
//                             mapAu.put("id", dataId);
//                             //当前数据详细信息
//                             Map<String, Object> current = jspActionDao.queryOne(mapAu);
//                             String originId = String.valueOf(current.get("originId"));
//                             sb.append(" where id = '").append(originId).append("'");
//                             sqls.add(sb.toString());
//                         }
//
//                     }
//                 }
//                 sqls.addAll(sqlUtil.genFlowSubmitSql(form, needFlow, modelId));
//
//                 if (!subModels.isEmpty()) {
//                     for (Model sub : subModels) {
//                         String table = sub.getTableName();
//                         //变更主表【对应】变更从表
//                         if (tableName.toUpperCase().endsWith(TableConst.MODIFYSUFFIX)) {
//                             table = table + TableConst.MODIFYSUFFIX;
//                         }
//                         List<String> subList = genFlowSubProcessParam(table, dataId);
//                         if (!subList.isEmpty()) {
//                             //主表走流程，明细表不要流程
//                             sqls.add(sqlUtil.genFlowSubDataTjSql(table, subList, needFlow));
//                         }
//                     }
//                 }
//             }
//             if (sqls.size() > 0) {
//                 jdbcflag = jdbcDao.executeSqlList(sqls, true);
//             }
//             if (jdbcflag) {
//                 rsflag = true;
//             } else {
//                 rsflag = false;
//             }
//         }
//         return rsflag;
//     }

    /**
     * 工作流提交
     */
//	@Override
//	public boolean submitFlow(List<TjForm> forms){
//		//对应模型
//		String modelId = forms.get(0).getTableName().split("_")[1];
//		Model model = cacheUtil.getModel(modelId);
//		String isMoreView=model.getIsMoreView()+""; //是否多视图
//		//判断是否有从表
//		List<Model> subModels = modelDao.isHasSub(modelId);
//		boolean needFlow = true;
//		boolean rsflag  = false;
//		boolean jdbcflag = false;
//		//数据字典
//		if("1".equals(model.getModelType())){
//			needFlow = false;
//		}else{
//			if(0==model.getIsWorkflow()){
//				needFlow = false;
//			}
//		}
//
//		//（当前批次提交）暂时缓存流程定义
//		Map<String, BusinessProcdef> pdMap = new HashMap<String, BusinessProcdef>();
//		//查询条件
//		Map<String, Object> cond = new HashMap<>();
//        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
//        cond.put("orgId", user.getOrganizationId());
//
//		//数据更新sql集合
//		List<String> sqls = new ArrayList<String>();
//		StringBuilder wfSql = new StringBuilder();
//
//		for(TjForm form : forms){
//			Map<String, Object> vars ;//流程流转参数
//			Map<String,Object> fromMap=new HashMap<>();
//			fromMap.put("id",form.getDataId());
//			fromMap.put("tableName",form.getTableName());
//			vars=wFparamUtil.formatWfParam(fromMap);
//
//
//			Map<String, Object> map = new HashMap<>();
//			String dataId = form.getDataId();
//			String tableName = form.getTableName();
//			map.put("id", dataId);
//			map.put("tableName", "T_"+modelId);
//			//提交之前的校验方法，若是校验通过 flagOnly 为true,否则,为false
//			boolean flagOnly=this.checkAttrOnly(form);
//			if(flagOnly){
//				//主数据
//				if(needFlow){
//					String orginTable = tableName;
//					if(tableName.toUpperCase().endsWith(TableConst.MODIFYSUFFIX))
//						orginTable = tableName.substring(0, tableName.lastIndexOf("_"));
//					cond.put("tableName", orginTable);  //业务类型
//					String operType = String.valueOf(Flag.toValue(form.getOperType(), "opertype"));
//					String key = operType; //操作类型
//					String dataType = form.getDataType(); //数据类型
//					if(!StringUtils.isBlank(dataType))
//					     key = key+"@"+dataType;
//
//					//业务关联流程设置
//					BusinessProcdef bp = null;
//					if("0".equals(isMoreView)){ //不是多视图
//						if(pdMap.containsKey(key)){
//							bp = pdMap.get(key);
//						}else{
//							cond.put("dataType", dataType);
//							cond.put("operType", operType);
//
//							bp = workFlowService.validate(cond); //流程定义
//							pdMap.put(key, bp);
//						}
//
//						//主数据不需要流程
//						if(bp == null){
//							needFlow = false;
//						}else{
//							//历史记录版本统一更新
//							sqls.add("UPDATE WF_RUN_HISTORY SET REV = rev+1 where DATA_ID = '" + dataId +"' and BUSI_TABLE='"+tableName+"'");
//							// 启动工作流
//							ProcessInstance instance = workFlowService.startFlow(bp, vars);
//			//				Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
//							List<Task> taskLst=taskService.createTaskQuery().processInstanceId(instance.getId()).list();
//							// 自动生成【送审】记录
//							wfSql.append("INSERT INTO WF_RUN_HISTORY (RID, WF_ID, BUSI_ID, BUSI_NAME, BUSI_TABLE, OPER_TYPE, ")
//								.append(" INSTANCE_ID, TASK_ID, NODE_ID, ASSIGNEE, DEFINITION_ID, PASS, ")
//								.append(" OPER_DATE, DATA_ID, OPINION, APPROVE_DATE, APPROVE_USER, REV ) VALUES ( ")
//								.append("WF_RUN_HISTORY_SEQ.nextval, ").append(bp.getId()).append(", ").append(bp.getBusiId())
//								.append(", '").append(bp.getBusiName()).append("','").append(form.getTableName()).append("', '")
//								.append(operType).append("', null, null, null, null, '").append(bp.getProcdefId())
//								.append("', null, sysdate, '").append(dataId).append("', '送审', sysdate")
//								.append(", '").append(user.getUserId()).append("', 0 ) ");
//							sqls.add(wfSql.toString());
//							wfSql.delete(0, wfSql.length());
//
//						for(int i=0;i<taskLst.size();i++){
//							/**
//                             * 并行
//							 */
//							List<SysUser> users= businessProcdefService.getTaskCandidateUsers(bp.getId(), taskLst.get(i).getTaskDefinitionKey());
//							List<String> userLst = new ArrayList<>();
//							for(SysUser u : users){
//								userLst.add(u.getUserId().toString());
//							}
//							String assignee="";
//							/**
//                             * List<SysUser> users= businessProcdefService.getTaskCandidateUsers(bp.getId(), activitiId);获取的是某个task节点的审批审批人,
//									 if(taskLst.size()==1){
//									 assignee=StringUtil.join(userLst, "user(", ")");
//									 }else{
//									 assignee=StringUtil.join(userLst.get(i), "user(", ")");
//									 }
//							 为什么   assignee=StringUtil.join(userLst.get(i), "user(", ")");这么写???
//							 */
//							assignee=StringUtil.join(userLst, "user(", ")");
//
//							Task task = taskLst.get(i);
//						    wfSql.append("INSERT INTO WF_RUN_DATA (RID, WF_ID, BUSI_ID, BUSI_NAME, OPER_TYPE, INSTANCE_ID, TASK_ID, ")
//						    	.append(" NODE_ID, ASSIGNEE, OPER_DATE, BUSI_TABLE, DATA_ID, DEFINITION_ID, TASKSTATE) VALUES ( ")
//						    	.append(" WF_RUN_DATA_SEQ.nextval, ").append(bp.getId()).append(", ").append(bp.getBusiId()).append(", '")
//						    	.append(bp.getBusiName()).append("', '").append(operType).append("', ").append(task.getProcessInstanceId())
//						    	.append(", ").append(task.getId()).append(", '").append(task.getTaskDefinitionKey()).append("', '")
//						    	.append(assignee).append("', sysdate, '").append(form.getTableName()).append("', '").append(dataId)
//						    	.append("', '").append(bp.getProcdefId()).append("', 1 ) ");
//					        sqls.add(wfSql.toString());
//							wfSql.delete(0, wfSql.length());
//						}
////					}else{
////
////					}
//					sqls.addAll(sqlUtil.genFlowSubmitSql(form, needFlow,modelId));
//
//					if(!subModels.isEmpty()){
//						for(Model sub : subModels){
//							String table = sub.getTableName();
//							//变更主表【对应】变更从表
//							if(tableName.toUpperCase().endsWith(TableConst.MODIFYSUFFIX)){
//								table = table + TableConst.MODIFYSUFFIX;
//							}
//							List<String> subList = genFlowSubProcessParam(table, dataId);
//							if(!subList.isEmpty()){
//								//主表走流程，明细表不要流程
//								sqls.add(sqlUtil.genFlowSubDataTjSql(table, subList, needFlow));
//							}
//						}
//					}
//				}
//			}
//
//				}
//			}
//		}
//
//		   if(sqls.size()>0){
//	           jdbcflag = jdbcDao.executeSqlList(sqls, true);
//	        }
//	        if(jdbcflag){
//	        	rsflag = true;
//	        }else{
//	        	rsflag = false;
//	        }
//			return rsflag;
//	}



    /**
     * 提交(用户信息不从session中取)--中纺srm接口用
     *
     * @param forms
     * @param user
     * @return
     * @author jyh
     */
    // @Override
    // public boolean submitFlow_zf(List<TjForm> forms, SysUser user) {
    //     //对应模型
    //     String modelId = forms.get(0).getTableName().split("_")[1];
    //     Model model = cacheUtil.getModel(modelId);
    //     String isMoreView = model.getIsMoreView() + ""; //是否多视图
    //     //判断是否有从表
    //     List<Model> subModels = modelDao.isHasSub(modelId);
    //     boolean needFlow = true;
    //     //数据字典
    //     if ("1".equals(model.getModelType())) {
    //         needFlow = false;
    //     } else {
    //         if (0 == model.getIsWorkflow()) {
    //             needFlow = false;
    //         }
    //     }
    //
    //     //（当前批次提交）暂时缓存流程定义
    //     Map<String, BusinessProcdef> pdMap = new HashMap<String, BusinessProcdef>();
    //     //查询条件
    //     Map<String, Object> cond = new HashMap<>();
    //     cond.put("orgId", user.getOrganizationId());
    //     //流程流转参数
    //     Map<String, Object> vars = new HashMap<>();
    //     //数据更新sql集合
    //     List<String> sqls = new ArrayList<String>();
    //     StringBuilder wfSql = new StringBuilder();
    //
    //     for (TjForm form : forms) {
    //
    //         Map<String, Object> map = new HashMap<>();
    //         String dataId = form.getDataId();
    //         String tableName = form.getTableName();
    //         map.put("id", dataId);
    //         map.put("tableName", "T_" + modelId);
    //         boolean flagOnly = this.checkAttrOnly(form);
    //         if (flagOnly) {
    //             //主数据
    //             if (needFlow) {
    //                 String orginTable = tableName;
    //                 if (tableName.toUpperCase().endsWith(TableConst.MODIFYSUFFIX)) {
    //                     orginTable = tableName.substring(0, tableName.lastIndexOf("_"));
    //                 }
    //                 cond.put("tableName", orginTable);  //业务类型
    //                 String operType = String.valueOf(Flag.toValue(form.getOperType(), "opertype"));
    //                 String key = operType; //操作类型
    //                 String dataType = form.getDataType(); //数据类型
    //                 if (!StringUtils.isBlank(dataType)) {
    //                     key = key + "@" + dataType;
    //                 }
    //
    //                 //业务关联流程设置
    //                 BusinessProcdef bp = null;
    //                 if ("0".equals(isMoreView)) { //不是多视图
    //                     if (pdMap.containsKey(key)) {
    //                         bp = pdMap.get(key);
    //                     } else {
    //                         cond.put("dataType", dataType);
    //                         cond.put("operType", operType);
    //
    //                         bp = workFlowService.validate(cond); //流程定义
    //                         pdMap.put(key, bp);
    //                     }
    //                 } else { //是多视图
    //                     map.put("modelId", modelId);
    //                     map.put("dataId", dataId);
    //                     map.put("operType", operType);
    //                     //由于万达多视图那个流程问题报错，目前这块先隐藏掉  ---刘晶 2017-08-14 21:45 pm
    //                     //	cond.put("views", viewDao.queryDataViewFlowsByDataId(map));
    //                     cond.put("dataType", dataType);
    //                     cond.put("operType", operType);
    //
    //                     bp = workFlowService.validate(cond); //流程定义
    //                     pdMap.put(key, bp);
    //                 }
    //
    //                 //主数据不需要流程
    //                 if (bp == null) {
    //                     needFlow = false;
    //                 } else {
    //                     //历史记录版本统一更新
    //                     sqls.add("UPDATE WF_RUN_HISTORY SET REV = rev+1 where DATA_ID = '" + dataId + "' and BUSI_TABLE='" + tableName + "'");
    //                     // 启动工作流
    //                     ProcessInstance instance = workFlowService.startFlow(bp, vars);
    //                     //				Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
    //                     List<Task> taskLst = taskService.createTaskQuery().processInstanceId(instance.getId()).list();
    //                     // 自动生成【送审】记录
    //                     wfSql.append("INSERT INTO WF_RUN_HISTORY (RID, WF_ID, BUSI_ID, BUSI_NAME, BUSI_TABLE, OPER_TYPE, ")
    //                             .append(" INSTANCE_ID, TASK_ID, NODE_ID, ASSIGNEE, DEFINITION_ID, PASS, ")
    //                             .append(" OPER_DATE, DATA_ID, OPINION, APPROVE_DATE, APPROVE_USER, REV ) VALUES ( ")
    //                             .append("WF_RUN_HISTORY_SEQ.nextval, ").append(bp.getId()).append(", ").append(bp.getBusiId())
    //                             .append(", '").append(bp.getBusiName()).append("','").append(form.getTableName()).append("', '")
    //                             .append(operType).append("', null, null, null, null, '").append(bp.getProcdefId())
    //                             .append("', null, sysdate, '").append(dataId).append("', '送审', sysdate")
    //                             .append(", '").append(user.getUserId()).append("', 0 ) ");
    //                     sqls.add(wfSql.toString());
    //                     wfSql.delete(0, wfSql.length());
    //
    //                     String activitiId = null;
    //                     if (instance.getActivityId() == null) {
    //                         activitiId = taskLst.get(0).getTaskDefinitionKey();
    //                     } else {
    //                         activitiId = instance.getActivityId();
    //                     }
    //
    //                     List<SysUser> users = businessProcdefService.getTaskCandidateUsers_zf(bp.getId(), activitiId);
    //                     List<String> userLst = new ArrayList<>();
    //                     for (SysUser u : users) {
    //                         userLst.add(u.getUserId().toString());
    //                     }
    //                     for (int i = 0; i < taskLst.size(); i++) {
    //                         String assignee = "";
    //                         if (taskLst.size() == 1) {
    //                             assignee = StringUtil.join(userLst, "user(", ")");
    //                         } else {
    //                             assignee = StringUtil.join(userLst.get(i), "user(", ")");
    //                         }
    //
    //                         Task task = taskLst.get(i);
    //                         wfSql.append("INSERT INTO WF_RUN_DATA (RID, WF_ID, BUSI_ID, BUSI_NAME, OPER_TYPE, INSTANCE_ID, TASK_ID, ")
    //                                 .append(" NODE_ID, ASSIGNEE, OPER_DATE, BUSI_TABLE, DATA_ID, DEFINITION_ID, TASKSTATE) VALUES ( ")
    //                                 .append(" WF_RUN_DATA_SEQ.nextval, ").append(bp.getId()).append(", ").append(bp.getBusiId()).append(", '")
    //                                 .append(bp.getBusiName()).append("', '").append(operType).append("', ").append(task.getProcessInstanceId())
    //                                 .append(", ").append(task.getId()).append(", '").append(task.getTaskDefinitionKey()).append("', '")
    //                                 .append(assignee).append("', sysdate, '").append(form.getTableName()).append("', '").append(dataId)
    //                                 .append("', '").append(bp.getProcdefId()).append("', 1 ) ");
    //                         sqls.add(wfSql.toString());
    //                         wfSql.delete(0, wfSql.length());
    //                     }
    //                 }
    //             }
    //             sqls.addAll(sqlUtil.genFlowSubmitSql(form, needFlow, modelId));
    //
    //             if (!subModels.isEmpty()) {
    //                 for (Model sub : subModels) {
    //                     String table = sub.getTableName();
    //                     //变更主表【对应】变更从表
    //                     if (tableName.toUpperCase().endsWith(TableConst.MODIFYSUFFIX)) {
    //                         table = table + TableConst.MODIFYSUFFIX;
    //                     }
    //                     List<String> subList = genFlowSubProcessParam(table, dataId);
    //                     if (!subList.isEmpty()) {
    //                         //主表走流程，明细表不要流程
    //                         sqls.add(sqlUtil.genFlowSubDataTjSql(table, subList, needFlow));
    //                     }
    //                 }
    //             }
    //         }
    //     }
    //
    //     return jdbcDao.executeSqlList(sqls, true);
    // }

    /**
     * 移动端工作流审核(移动端登录用户信息不存入session)
     * @param forms
     * @return
     * @author jyh
     * @date 2017-06-20
     */
//	@Override
//	public boolean approveFlowMobile(List<ShForm> forms, String userId){
//		Map<String, Object> param = new HashMap<>();
//		String modelId=forms.get(0).getTableName().split("_")[1];
//		//查询从表
//		List<Model> subModels = modelDao.isHasSub(modelId);
//
//		//数据更新的sql集合
//		List<String> sqls = new ArrayList<String>();
//        StringBuilder wfSql = new StringBuilder();
//
//		Map<String, Object> vars = new HashMap<>();
//        for(ShForm form : forms){
//			String taskId=form.getTaskId();
//			//当前审核记录
//			RunRecord record = runRecordDao.queryByTaskId(taskId);
//
//			String insId=form.getInstanceId();
//        	vars.put(CustomConst.PASS, form.isPass());
//			boolean isEnd = workFlowService.completeTask(userId, taskId, vars, record.getWfId());
//			sqls.addAll(sqlUtil.genFlowApproveSql(form, isEnd , modelId));
//
//			List<String> userLst = new ArrayList<>();
//			//一个任务审核完后改为已经审核完成，待整个流程走完后根据实例id删除，减少表负荷
//			sqls.add("UPDATE wf_run_data SET TASKSTATE='2' where TASK_id = " + taskId);
//			//流程是否结束--true 结束    --false 未结束
//			if(isEnd){
//				//减少表数据负荷
//				sqls.add("delete wf_run_data where instance_id = " + insId);
//				//审核通过后，自动写入分发表
//				if(form.isPass()){
//					param.put("tableName",form.getTableName());
//					param.put("ids", form.getDataId());
//					param.put("subModels", subModels);
//					this.insertDis(param);//审核通过插入分发表中
////					autoCodeService.autoCode(modelId,form.getDataId());//自动附码
//				}
//				//判断是否有从表
//				if(!subModels.isEmpty()){
//					for(Model sub : subModels){
//						String table = sub.getTableName();
//						//变更主表【对应】变更从表
//						if(form.getTableName().toUpperCase().endsWith(TableConst.MODIFYSUFFIX)){
//							table = table + TableConst.MODIFYSUFFIX;
//						}
////						Map<String, Object> resMap = sqlUtil.genFlowSubDatasParam(table, form.getDataId());
////						List<String> subIds = (List<String>) resMap.get("idLst");
////						List<Map<String, Object>> subDatas = (List<Map<String, Object>>) resMap.get("datas");
//						List<Map<String, Object>> datas = sqlUtil.genFlowSubDatasParam(table, form.getDataId());
//						if(!datas.isEmpty()){
//							//主表走流程，明细表不要流程
//							sqls.addAll(sqlUtil.genFlowSubDataShSql(form, table, datas));
//						}
//					}
//				}
//			}else{
//				//下一个任务
//				List<Task> next = taskService.createTaskQuery().processInstanceId(form.getInstanceId()).list();
//				//Map<String, Object> variables = taskService.getVariables(next.get(0).getId());
//
//				List<SysUser> users= businessProcdefService.getTaskCandidateUsers(
//											record.getWfId(), next.get(0).getTaskDefinitionKey());
//				for(SysUser u : users){
//					userLst.add(u.getUserId().toString());
//				}
//				for(int i=0; i<next.size(); i++){
//					String assignee="";
//					if(next.size()==1){
//						assignee=StringUtil.join(userLst, "user(", ")");
//					}else{
//						assignee=StringUtil.join(userLst.get(i), "user(", ")");
//					}
//					Task task = next.get(i);
//					//插入待办
//					int hasTaskId=businessProcdefDao.queryByTaskId(task.getId());
//					if(hasTaskId==0){
//					    wfSql.append("INSERT INTO WF_RUN_DATA (RID, WF_ID, BUSI_ID, BUSI_NAME, OPER_TYPE, INSTANCE_ID, TASK_ID, ")
//				    	.append(" NODE_ID, ASSIGNEE, OPER_DATE, BUSI_TABLE, DATA_ID, DEFINITION_ID, TASKSTATE) VALUES ( ")
//				    	.append(" WF_RUN_DATA_SEQ.nextval, ").append(record.getWfId()).append(", ").append(record.getBusiId())
//				    	.append(", '").append(record.getBusiName()).append("', '").append(record.getOperType()).append("', ")
//				    	.append(task.getProcessInstanceId()).append(", ").append(task.getId()).append(", '")
//				    	.append(task.getTaskDefinitionKey()).append("', '").append(assignee).append("', sysdate, '")
//				    	.append(form.getTableName()).append("', '").append(form.getDataId())
//				    	.append("', '").append(record.getDefinitionId()).append("', 1 ) ");
//						sqls.add(wfSql.toString());
//						wfSql.delete(0, wfSql.length());
//					}
//				}
//			}
//			//String approvers = StringUtil.join(userLst, "", ",");
//			int result = form.isPass() ? 1 : 0;
//			/**
//			 * 刘晶 2017-6-19 13:49 星期一
//			 * 由于从获取的record 对象的operdate日期格式，结尾不知道什么原因多了(.0)
//			 * 导致审核流程报错（insert sql日期那块报错）
//			 * 现在先这样处理，后续，要是找到原因，在解决
//			 */
//			String operDate="";
//			String aa = record.getOperDate().toString();
//			if(aa.indexOf(".")!=-1){
//				operDate = aa.substring(0, aa.length()-2);
//			}else{
//			    operDate = aa.substring(0, aa.length());
//			}
//			/**----------------------------------------------------------------*/
//			wfSql.append("INSERT INTO WF_RUN_HISTORY (RID, WF_ID, BUSI_ID, BUSI_NAME, BUSI_TABLE, OPER_TYPE, ")
//				.append(" INSTANCE_ID, TASK_ID, NODE_ID, ASSIGNEE, DEFINITION_ID, PASS, ")
//				.append(" OPER_DATE, DATA_ID, OPINION, APPROVE_DATE, APPROVE_USER, REV ) VALUES ( ")
//				.append("WF_RUN_HISTORY_SEQ.nextval, ").append(record.getWfId()).append(", ").append(record.getBusiId())
//				.append(", '").append(record.getBusiName()).append("','").append(form.getTableName()).append("', '")
//				.append(record.getOperType()).append("', ").append(record.getInstanceId()).append(", ").append(record.getTaskId())
//				.append(", '").append(record.getNodeId()).append("', '").append(record.getAssignee()).append("', '")
//				//.append(", '").append(record.getNodeId()).append("', '").append(approvers).append("', '")
//				//.append(", '").append(record.getNodeId()).append("', '").append(user.getUserId()).append("', '")
//				.append(record.getDefinitionId()).append("', '").append(result).append("', to_date('")
//				.append(operDate).append("', 'yyyy-MM-dd hh24:mi:ss'), '").append(form.getDataId()).append("', '")
//				//.append(record.getOperDate()).append("', 'yyyy-MM-dd hh24:mi:ss'), '").append(form.getDataId()).append("', '")
//				.append(form.getOpinion()).append("', sysdate, '").append(userId).append("', 0 ) ");
//			sqls.add(wfSql.toString());
//			wfSql.delete(0, wfSql.length());
//		}
//
//		boolean flag=jdbcDao.executeSqlList(sqls, true);
//		return flag;
//	}

    /**
     * 工作流审核
     */
    // @Override
//     public String approveFlow(List<ShForm> forms, String userId, String type) {
//         Map<String, Object> retmap = new HashMap<>();//返回结果
//         Map<String, Object> param = new HashMap<>();
//         String modelId = forms.get(0).getTableName().split("_")[1];
//
// //        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
//         //数据更新的sql集合
//         List<String> sqls = new ArrayList<String>();
//         StringBuilder wfSql = new StringBuilder();
//
//
//         StringBuffer sbret = new StringBuffer();
//         int sucCount = 0;
//         int codeOrDisfailCount = 0;
// //        for(ShForm form : forms){
//         for (int j = 0; j < forms.size(); j++) {
//             ShForm form = forms.get(j);
//             String err = "";
//
//             Map<String, Object> vars;//流程流转参数
//             Map<String, Object> fromMap = new HashMap<>();
//             fromMap.put("id", form.getDataId());
//             fromMap.put("tableName", form.getTableName());
//             fromMap.put("type", "approve");
//             vars = wFparamUtil.formatWfParam(fromMap);
//
//             String taskId = form.getTaskId();
//             //当前审核记录
//             RunRecord record = runRecordDao.queryByTaskId(taskId);
//
//             String insId = form.getInstanceId();
// //			String userId = user.getUserId().toString();
//             vars.put(CustomConst.PASS, form.isPass());
//             boolean isEnd = false;
//             try {
//                 isEnd = workFlowService.completeTask(userId, taskId, vars, record.getWfId());
// //				isEnd = workFlowService.completeTask(userId, taskId, vars, record);
//                 sucCount++;
//             } catch (Exception e1) {
//                 err = "审核失败:" + getErrorStr(e1.getMessage());//.substring(0, 100);
//             }
//             sqls.addAll(sqlUtil.genFlowApproveSql(form, isEnd, modelId));
//
//             List<String> userLst = new ArrayList<>();
//             //一个任务审核完后改为已经审核完成，待整个流程走完后根据实例id删除，减少表负荷
//             sqls.add("UPDATE wf_run_data SET TASKSTATE='2' where TASK_id = " + taskId);
//             //流程是否结束--true 结束    --false 未结束
//             if (isEnd && StringUtils.isEmpty(err)) {
//                 //减少表数据负荷
//                 sqls.add("delete wf_run_data where instance_id = " + insId);
//                 //查询从表
//                 List<Model> subModels = modelDao.isHasSub(modelId);
//                 //判断是否有从表
//                 try {
//                     if (!subModels.isEmpty()) {
//                         for (Model sub : subModels) {
//                             String table = sub.getTableName();
//                             //变更主表【对应】变更从表
//                             if (form.getTableName().toUpperCase().endsWith(TableConst.MODIFYSUFFIX)) {
//                                 table = table + TableConst.MODIFYSUFFIX;
//                             }
//                             List<Map<String, Object>> datas = sqlUtil.genFlowSubDatasParam(table, form.getDataId());
//                             if (!datas.isEmpty()) {
//                                 //主表走流程，明细表不要流程
//                                 sqls.addAll(sqlUtil.genFlowSubDataShSql(form, table, datas));
//                             }
//                         }
//                     }
//                 } catch (Exception e) {
//                     err = "从表审核错误" + getErrorStr(e.getMessage());//.substring(0, 100);
//                 }
//                 if (form.isPass() && "审核".equals(form.getOperType())) {//当期最后一级审核,并且审核通过,则对于需要自动附码的模型进行附码
//                     String[] strArr = autoCodeService.autoCode(modelId, form.getDataId());//自动附码
//                     if (!StringUtils.isEmpty(strArr[1])) {
//                         err = "自动附码失败:" + strArr[1];
//                         codeOrDisfailCount++;
//                     }
//                 }
// //				if(form.isPass() && "提交".equals(form.getOperType())){//当期最后一级审核,并且审核通过,则对于需要自动附码的模型进行附码
// //					String[] strArr = autoCodeService.autoCode(modelId,form.getDataId());//自动附码
// //					if(!StringUtils.isEmpty(strArr[1])){
// //						err = "自动附码失败:"+strArr[1];
// //						codeOrDisfailCount++;
// //					}
// //				}
//                 //审核通过后，自动写入分发表
//                 if (StringUtils.isEmpty(err) && form.isPass()) {//如果当前是最后一级审核,并且审核通过,如果当前模型需要自动附码并且自动附码成功,则写入分发表
//                     param.put("tableName", form.getTableName());
//                     param.put("ids", form.getDataId());
//                     param.put("subModels", subModels);
//                     param.put("operType", form.getOperType());
//
//                     try {
//                         this.insertDis(param);//审核通过插入分发表中
//                     } catch (Exception e) {
//                         err = "写入分发表异常" + getErrorStr(e.getMessage());//.substring(0, 100);
//                         codeOrDisfailCount++;
//                     }
//                 }
//             } else if (StringUtils.isEmpty(err)) {
//                 //下一个任务
//                 try {
//                     List<Task> next = taskService.createTaskQuery().processInstanceId(form.getInstanceId()).list();
//
//                     List<SysUser> users = businessProcdefService.getTaskCandidateUsers(
//                             record.getWfId(), next.get(0).getTaskDefinitionKey());
//                     for (SysUser u : users) {
//                         userLst.add(u.getUserId().toString());
//                     }
//                     for (int i = 0; i < next.size(); i++) {
//                         String assignee = "";
//                         if (next.size() == 1) {
//                             assignee = StringUtil.join(userLst, "user(", ")");
//                         } else {
//                             assignee = StringUtil.join(userLst.get(i), "user(", ")");
//                         }
//                         Task task = next.get(i);
//                         //插入待办
//                         int hasTaskId = businessProcdefDao.queryByTaskId(task.getId());
//                         if (hasTaskId == 0) {
//                             sqls.add(joinRunSql(record, task, form, assignee));
//                             wfSql.delete(0, wfSql.length());
//                         }
//                     }
//                 } catch (Exception e) {
//                     err = getErrorStr(e.getMessage());//.substring(0,100);
//                 }
//
//             }
//             int result = form.isPass() ? 1 : 0;
//
//             sqls.add(joinWfSql(record, result, form, userId));
//             wfSql.delete(0, wfSql.length());
//
//             if (!StringUtils.isEmpty(err)) {
//                 sbret.append("&nbsp;&nbsp;&nbsp;第" + (j + 1) + "条数据" + err + "<br>");
//             }
//         }
//
//         boolean flag = jdbcDao.executeSqlList(sqls, true);
//         if (flag) {//批量更新数据库,修改数据状态等一系列操作成功
//             retmap.put("state", true);
//         } else {//如果批量更新数据库失败,流程可能已经正常结束,这个时候流程已经结束,但是数据状态还是审核中,此时只能操作数据库修改数据(主表,wf_run_data表,act_ru_task表)
//             sbret = new StringBuffer();
//             sbret.append("审核失败:	批量更新数据库失败, 请联系管理员!");
//             retmap.put("state", false);
//         }
//
//         retmap.put("totalCount", forms.size());//审核数据总数量
//         retmap.put("sucCount", sucCount);//审核成功的数据数量
//         retmap.put("errInfo", sbret.toString());//错误日志
//         retmap.put("codeOrDisfailCount", codeOrDisfailCount);//分发或者自动附码失败的数量
//         String retStr = "";
//         if ("PC".equals(type)) {
//             retStr = retStrFun(retmap);
//         } else {
//             retStr = retStrFunMob(retmap);
//         }
//         return retStr;
//     }

    /**
     * (中国万达集团主数据工作流专用)
     */
    // @Override
    // public String approveFlowToWandaWorkflow(ShForm form, boolean isEnd) {
    //     Map<String, Object> retmap = new HashMap<>();// 返回结果
    //     Map<String, Object> param = new HashMap<>();
    //     String modelId = form.getTableName().split("_")[1];
    //     // 数据更新的sql集合
    //     List<String> sqls = new ArrayList<String>();
    //     StringBuilder wfSql = new StringBuilder();
    //     Map<String, Object> vars = new HashMap<>();
    //     StringBuffer sbret = new StringBuffer();
    //     int sucCount = 0;
    //     int codeOrDisfailCount = 0;
    //     String err = "";
    //     sqls.addAll(sqlUtil.genFlowApproveSql(form, isEnd, modelId));
    //
    //     List<String> userLst = new ArrayList<>();
    //     if (isEnd && StringUtils.isEmpty(err)) {
    //         sucCount++;
    //         List<Model> subModels = modelDao.isHasSub(modelId);
    //         // 判断是否有从表
    //         try {
    //             if (!subModels.isEmpty()) {
    //                 for (Model sub : subModels) {
    //                     String table = sub.getTableName();
    //                     // 变更主表【对应】变更从表
    //                     if (form.getTableName().toUpperCase().endsWith(TableConst.MODIFYSUFFIX)) {
    //                         table = table + TableConst.MODIFYSUFFIX;
    //                     }
    //                     List<Map<String, Object>> datas = sqlUtil.genFlowSubDatasParam(table, form.getDataId());
    //                     if (!datas.isEmpty()) {
    //                         // 主表走流程，明细表不要流程
    //                         sqls.addAll(sqlUtil.genFlowSubDataShSql(form, table, datas));
    //                     }
    //                 }
    //             }
    //         } catch (Exception e) {
    //             err = "从表审核错误" + getErrorStr(e.getMessage());// .substring(0,
    //             // 100);
    //         }
    //         if (form.isPass() && "审核".equals(form.getOperType())) {// 当期最后一级审核,并且审核通过,则对于需要自动附码的模型进行附码
    //             String[] strArr = autoCodeService.autoCode(modelId, form.getDataId());// 自动附码
    //             if (!StringUtils.isEmpty(strArr[1])) {
    //                 err = "自动附码失败:" + strArr[1];
    //                 codeOrDisfailCount++;
    //             }
    //         }
    //         // 审核通过后，自动写入分发表
    //         if (StringUtils.isEmpty(err) && form.isPass()) {// 如果当前是最后一级审核,并且审核通过,如果当前模型需要自动附码并且自动附码成功,则写入分发表
    //             param.put("tableName", form.getTableName());
    //             param.put("ids", form.getDataId());
    //             param.put("subModels", subModels);
    //             try {
    //                 this.insertDis(param);// 审核通过插入分发表中
    //             } catch (Exception e) {
    //                 err = "写入分发表异常" + getErrorStr(e.getMessage());
    //                 codeOrDisfailCount++;
    //             }
    //         }
    //     }
    //     int result = form.isPass() ? 1 : 0;
    //     boolean flag = jdbcDao.executeSqlList(sqls, true);
    //     if (flag) {// 批量更新数据库,修改数据状态等一系列操作成功
    //         retmap.put("state", true);
    //     } else {// 如果批量更新数据库失败,流程可能已经正常结束,这个时候流程已经结束,但是数据状态还是审核中,此时只能操作数据库修改数据(主表,wf_run_data表,act_ru_task表)
    //         sbret = new StringBuffer();
    //         sbret.append("审核失败:	批量更新数据库失败, 请联系管理员!");
    //         retmap.put("state", false);
    //     }
    //     retmap.put("totalCount", 1);// 审核数据总数量
    //     retmap.put("sucCount", sucCount);// 审核成功的数据数量
    //     retmap.put("errInfo", sbret.toString());// 错误日志
    //     retmap.put("codeOrDisfailCount", codeOrDisfailCount);// 分发或者自动附码失败的数量
    //     String retStr = retStrFun(retmap);
    //     return retStr;
    // }

    private String getErrorStr(String errorInfo) {
//		return errorInfo;
        return errorInfo.substring(0, errorInfo.length() > 100 ? 100 : errorInfo.length());
    }

    private String retStrFun(Map<String, Object> retmap) {
        StringBuffer sbStr = new StringBuffer();
        int totalCount = (int) retmap.get("totalCount");//审核数据总数量
        int sucCount = (int) retmap.get("sucCount");//审核成功的数据数量
        int codeOrDisfailCount = (int) retmap.get("codeOrDisfailCount");//分发或者自动附码失败的数量
        String errInfo = (String) retmap.get("errInfo");//错误日志
        sbStr.append("共审核" + totalCount + "条记录<br>");
        sbStr.append("   &nbsp;&nbsp;&nbsp;成功<font color='green'>" + sucCount + "条记录<br>");
        if (totalCount - sucCount > 0) {
            sbStr.append("  &nbsp;&nbsp;&nbsp;失败" + (totalCount - sucCount) + "条记录,");
        }
        if (codeOrDisfailCount > 0) {
            sbStr.append("  &nbsp;&nbsp;&nbsp;共" + codeOrDisfailCount + "条记录分发失败<br>");
        } else {
            sbStr.append("<br>");
        }
        if (!StringUtils.isEmpty(errInfo)) {
            sbStr.append("   失败原因:<br>" + errInfo);
        }


        return sbStr.toString();
    }

    //移动端返回消息
    private String retStrFunMob(Map<String, Object> retmap) {
        StringBuffer sbStr = new StringBuffer();
        int totalCount = (int) retmap.get("totalCount");//审核数据总数量
        int sucCount = (int) retmap.get("sucCount");//审核成功的数据数量
        int codeOrDisfailCount = (int) retmap.get("codeOrDisfailCount");//分发或者自动附码失败的数量
        String errInfo = (String) retmap.get("errInfo");//错误日志
        sbStr.append("共审核" + totalCount + "条记录");
        sbStr.append("成功" + sucCount + "条记录");
        if (totalCount - sucCount > 0) {
            sbStr.append("失败" + (totalCount - sucCount) + "条记录,");
        }
        if (codeOrDisfailCount > 0) {
            sbStr.append("共" + codeOrDisfailCount + "条记录分发失败");
        } else {
            sbStr.append("");
        }
        if (!StringUtils.isEmpty(errInfo)) {
            sbStr.append("失败原因:" + errInfo);
        }


        return sbStr.toString();
    }

    // private String joinRunSql(RunRecord record, Task task, ShForm form, String assignee) {
    //     StringBuffer wfSql = new StringBuffer();
    //     wfSql.append("INSERT INTO WF_RUN_DATA (RID, WF_ID, BUSI_ID, BUSI_NAME, OPER_TYPE, INSTANCE_ID, TASK_ID, ")
    //             .append(" NODE_ID, ASSIGNEE, OPER_DATE, BUSI_TABLE, DATA_ID, DEFINITION_ID, TASKSTATE) VALUES ( ")
    //             .append(" WF_RUN_DATA_SEQ.nextval, ").append(record.getWfId()).append(", ").append(record.getBusiId())
    //             .append(", '").append(record.getBusiName()).append("', '").append(record.getOperType()).append("', ")
    //             .append(task.getProcessInstanceId()).append(", ").append(task.getId()).append(", '")
    //             .append(task.getTaskDefinitionKey()).append("', '").append(assignee).append("', sysdate, '")
    //             .append(form.getTableName()).append("', '").append(form.getDataId())
    //             .append("', '").append(record.getDefinitionId()).append("', 1 ) ");
    //     return wfSql.toString();
    // }

    // private String joinWfSql(RunRecord record, int result, ShForm form, String userId) {
    //     StringBuffer wfSql = new StringBuffer();
    //     /**
    //      * ---wy调整---
    //      * 刘晶 2017-6-19 13:49 星期一
    //      * 由于从获取的record 对象的operdate日期格式，结尾不知道什么原因多了(.0) 导致审核流程报错（insert sql日期那块报错） 现在先这样处理，后续，要是找到原因，在解决
    //      */
    //     String operDate = "";
    //     String aa = record.getOperDate().toString();
    //     if (aa.indexOf(".") != -1) {
    //         operDate = aa.substring(0, aa.length() - 2);
    //     } else {
    //         operDate = aa.substring(0, aa.length());
    //     }
    //     wfSql.append("INSERT INTO WF_RUN_HISTORY (RID, WF_ID, BUSI_ID, BUSI_NAME, BUSI_TABLE, OPER_TYPE, ")
    //             .append(" INSTANCE_ID, TASK_ID, NODE_ID, ASSIGNEE, DEFINITION_ID, PASS, ")
    //             .append(" OPER_DATE, DATA_ID, OPINION, APPROVE_DATE, APPROVE_USER, REV ) VALUES ( ")
    //             .append("WF_RUN_HISTORY_SEQ.nextval, ").append(record.getWfId()).append(", ").append(record.getBusiId())
    //             .append(", '").append(record.getBusiName()).append("','").append(form.getTableName()).append("', '")
    //             .append(record.getOperType()).append("', ").append(record.getInstanceId()).append(", ").append(record.getTaskId())
    //             .append(", '").append(record.getNodeId()).append("', '").append(record.getAssignee()).append("', '")
    //             .append(record.getDefinitionId()).append("', '").append(result).append("', to_date('")
    //             .append(operDate).append("', 'yyyy-MM-dd hh24:mi:ss'), '").append(form.getDataId()).append("', '")
    //             .append(form.getOpinion()).append("', sysdate, '").append(userId).append("', 0 ) ");
    //     return wfSql.toString();
    // }


//
//	/**
//	 * 工作流审核
//	 */
//	@Override
//	public boolean approveFlow(List<ShForm> forms){
//		Map<String, Object> param = new HashMap<>();
//		String modelId=forms.get(0).getTableName().split("_")[1];
//		//查询从表
//		List<Model> subModels = modelDao.isHasSub(modelId);
//
//        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
//		//数据更新的sql集合
//		List<String> sqls = new ArrayList<String>();
//        StringBuilder wfSql = new StringBuilder();
//
//		Map<String, Object> vars = new HashMap<>();
//        for(ShForm form : forms){
//			String taskId=form.getTaskId();
//			//当前审核记录
//			RunRecord record = runRecordDao.queryByTaskId(taskId);
//
//			String insId=form.getInstanceId();
//			String userId = user.getUserId().toString();
//        	vars.put(CustomConst.PASS, form.isPass());
//			boolean isEnd = workFlowService.completeTask(userId, taskId, vars, record.getWfId());
//			sqls.addAll(sqlUtil.genFlowApproveSql(form, isEnd , modelId));
//
//			List<String> userLst = new ArrayList<>();
//			//一个任务审核完后改为已经审核完成，待整个流程走完后根据实例id删除，减少表负荷
//			sqls.add("UPDATE wf_run_data SET TASKSTATE='2' where TASK_id = " + taskId);
//			//流程是否结束--true 结束    --false 未结束
//			if(isEnd){
//				//减少表数据负荷
//				sqls.add("delete wf_run_data where instance_id = " + insId);
//				//审核通过后，自动写入分发表
//				if(form.isPass()){
//					param.put("tableName",form.getTableName());
//					param.put("ids", form.getDataId());
//					param.put("subModels", subModels);
//					this.insertDis(param);//审核通过插入分发表中
////					autoCodeService.autoCode(modelId,form.getDataId());//自动附码
//				}
//				//判断是否有从表
//				if(!subModels.isEmpty()){
//					for(Model sub : subModels){
//						String table = sub.getTableName();
//						//变更主表【对应】变更从表
//						if(form.getTableName().toUpperCase().endsWith(TableConst.MODIFYSUFFIX)){
//							table = table + TableConst.MODIFYSUFFIX;
//						}
////						Map<String, Object> resMap = sqlUtil.genFlowSubDatasParam(table, form.getDataId());
////						List<String> subIds = (List<String>) resMap.get("idLst");
////						List<Map<String, Object>> subDatas = (List<Map<String, Object>>) resMap.get("datas");
//						List<Map<String, Object>> datas = sqlUtil.genFlowSubDatasParam(table, form.getDataId());
//						if(!datas.isEmpty()){
//							//主表走流程，明细表不要流程
//							sqls.addAll(sqlUtil.genFlowSubDataShSql(form, table, datas));
//						}
//					}
//				}
//			}else{
//				//下一个任务
//				List<Task> next = taskService.createTaskQuery().processInstanceId(form.getInstanceId()).list();
//				//Map<String, Object> variables = taskService.getVariables(next.get(0).getId());
//
//				List<SysUser> users= businessProcdefService.getTaskCandidateUsers(
//											record.getWfId(), next.get(0).getTaskDefinitionKey());
//				for(SysUser u : users){
//					userLst.add(u.getUserId().toString());
//				}
//				for(int i=0; i<next.size(); i++){
//					String assignee="";
//					if(next.size()==1){
//						assignee=StringUtil.join(userLst, "user(", ")");
//					}else{
//						assignee=StringUtil.join(userLst.get(i), "user(", ")");
//					}
//					Task task = next.get(i);
//					//插入待办
//					int hasTaskId=businessProcdefDao.queryByTaskId(task.getId());
//					if(hasTaskId==0){
//					    wfSql.append("INSERT INTO WF_RUN_DATA (RID, WF_ID, BUSI_ID, BUSI_NAME, OPER_TYPE, INSTANCE_ID, TASK_ID, ")
//				    	.append(" NODE_ID, ASSIGNEE, OPER_DATE, BUSI_TABLE, DATA_ID, DEFINITION_ID, TASKSTATE) VALUES ( ")
//				    	.append(" WF_RUN_DATA_SEQ.nextval, ").append(record.getWfId()).append(", ").append(record.getBusiId())
//				    	.append(", '").append(record.getBusiName()).append("', '").append(record.getOperType()).append("', ")
//				    	.append(task.getProcessInstanceId()).append(", ").append(task.getId()).append(", '")
//				    	.append(task.getTaskDefinitionKey()).append("', '").append(assignee).append("', sysdate, '")
//				    	.append(form.getTableName()).append("', '").append(form.getDataId())
//				    	.append("', '").append(record.getDefinitionId()).append("', 1 ) ");
//						sqls.add(wfSql.toString());
//						wfSql.delete(0, wfSql.length());
//					}
//				}
//			}
//			//String approvers = StringUtil.join(userLst, "", ",");
//			int result = form.isPass() ? 1 : 0;
//			/**
//			 * 刘晶 2017-6-19 13:49 星期一
//			 * 由于从获取的record 对象的operdate日期格式，结尾不知道什么原因多了(.0)
//			 * 导致审核流程报错（insert sql日期那块报错）
//			 * 现在先这样处理，后续，要是找到原因，在解决
//			 */
//			String operDate="";
//			String aa = record.getOperDate().toString();
//			if(aa.indexOf(".")!=-1){
//				operDate = aa.substring(0, aa.length()-2);
//			}else{
//			    operDate = aa.substring(0, aa.length());
//			}
//			/**----------------------------------------------------------------*/
//			wfSql.append("INSERT INTO WF_RUN_HISTORY (RID, WF_ID, BUSI_ID, BUSI_NAME, BUSI_TABLE, OPER_TYPE, ")
//				.append(" INSTANCE_ID, TASK_ID, NODE_ID, ASSIGNEE, DEFINITION_ID, PASS, ")
//				.append(" OPER_DATE, DATA_ID, OPINION, APPROVE_DATE, APPROVE_USER, REV ) VALUES ( ")
//				.append("WF_RUN_HISTORY_SEQ.nextval, ").append(record.getWfId()).append(", ").append(record.getBusiId())
//				.append(", '").append(record.getBusiName()).append("','").append(form.getTableName()).append("', '")
//				.append(record.getOperType()).append("', ").append(record.getInstanceId()).append(", ").append(record.getTaskId())
//				.append(", '").append(record.getNodeId()).append("', '").append(record.getAssignee()).append("', '")
//				//.append(", '").append(record.getNodeId()).append("', '").append(approvers).append("', '")
//				//.append(", '").append(record.getNodeId()).append("', '").append(user.getUserId()).append("', '")
//				.append(record.getDefinitionId()).append("', '").append(result).append("', to_date('")
//				.append(operDate).append("', 'yyyy-MM-dd hh24:mi:ss'), '").append(form.getDataId()).append("', '")
//				//.append(record.getOperDate()).append("', 'yyyy-MM-dd hh24:mi:ss'), '").append(form.getDataId()).append("', '")
//				.append(form.getOpinion()).append("', sysdate, '").append(user.getUserId()).append("', 0 ) ");
//			sqls.add(wfSql.toString());
//			wfSql.delete(0, wfSql.length());
//		}
//
//		boolean flag=jdbcDao.executeSqlList(sqls, true);
//		return flag;
//	}

    /**
     * 分发
     */
    @Override
    public boolean insertDis(Map<String, Object> param) {
        param.put("mainTabName", "");
        //主表分发
        List<String> sqls = sqlUtil.genDisInsertSql(param);
        //查询从表   刘晶先将主从表模型从表分发注释
        String tabName = param.get("tableName").toString();
        String tableName = tabName.endsWith(TableConst.MODIFYSUFFIX) ? tabName.substring(0, tabName.lastIndexOf("_")) : tabName;
        String modelId = tableName.split("_")[1];
        List<Model> subModels = Collections.EMPTY_LIST;
        if (param.containsKey("subModels")) {
            subModels = (List<Model>) param.get("subModels");
        } else {
            subModels = modelDao.isHasSub(modelId);
        }
        if (!subModels.isEmpty()) {
            for (Model sub : subModels) {
//				Map<String, Object> subParam = genSubProcessParam(sub.getTableName()+"_update", param.get("ids").toString());
//				Map<String, Object> subParam = genSubProcessParam(sub.getTableName()+"_UPDATE", param.get("ids").toString());
                Map<String, Object> subParam = genSubProcessParam(sub.getTableName() + TableConst.MODIFYSUFFIX, param.get("ids").toString());
                if (subParam != null) {
                    //递归调用
                    if (tabName.endsWith(TableConst.MODIFYSUFFIX)) {//判断表的结尾
                        subParam.put("tableName", sub.getTableName() + TableConst.MODIFYSUFFIX);
                    }
                    subParam.put("mainTabName", tableName);
                    sqls.addAll(sqlUtil.genDisInsertSql(subParam));
                }
            }
        }
        return jdbcDao.executeSqlList(sqls, true);
    }

    /**
     * 获取从表的ID集合
     *
     * @param tableName
     * @param id
     * @return
     */
    private List<String> genFlowSubProcessParam(String tableName, String id) {
        Map<String, Object> result_map = new HashMap<>();
        result_map.put("tableName", tableName);
        result_map.put("idLst", Arrays.asList(id));
        result_map.put("idType", "MAINID");
        return jspActionDao.selectSubDataIdList(result_map);
    }

// 	abstract class callBack<T>{
// 		private T bean;
// 		public callBack(T bean){
// 			this.bean = bean;
// 		}
//
// 		abstract T execute();
// 	}

    /**
     * 数据审核<br/>
     * 已被 approveFlow 替代
     */
    @Override
    @Deprecated
    public boolean approve(Map<String, Object> param) {
        // 主表sql集合
        List<String> sqls = sqlUtil.genApproveSql(param);

        //判断是否有从表
        List<Model> subModels = modelDao.isHasSub(param.get("tableName").toString().split("_")[1]);
        if (!subModels.isEmpty()) {
            //组装信息 ID ♀ opinion ♀ Y/N ♀ operType [♂]
            String[] items = param.get("infos").toString().split("♂");
            for (String item : items) {
                Map<String, Object> cddata = new HashMap<>();
                String[] pms = item.split("♀");
                for (Model sub : subModels) {
                    if (Flag.OPER_2.getDesc().equals(pms[3])) {
                        cddata.put("tableName", sub.getTableName());
                    } else {
                        cddata.put("tableName", sub.getTableName() + TableConst.MODIFYSUFFIX);
                    }
                    //cddata.put("idLst", item.substring(0, item.indexOf("♀")));
                    cddata.put("idValue", pms[0]);
                    cddata.put("idType", "MAINID");
                    //查询从表数据
                    List<String> resLst = jspActionDao.selectSubDataIdList(cddata);
                    if (!resLst.isEmpty()) {
                        StringBuilder subInfos = new StringBuilder();
                        String commonStr = item.substring(item.indexOf("♀"));
                        for (int j = 0; j < resLst.size(); j++) {
                            subInfos.append(resLst.get(j)).append(commonStr).append("♂");
                        }
                        //更换参数， 递归获取从表sql
                        Map<String, Object> subParam = new HashMap<>();
                        subParam.put("infos", subInfos.substring(0, subInfos.length() - 1));
                        subParam.put("tableName", sub.getTableName());
                        sqls.addAll(sqlUtil.genApproveSql(subParam));
                    }
                }
            }
        }
        boolean flag = jdbcDao.executeSqlList(sqls, true);
        return flag;
    }

    /**
     * 导出===刘晶，新版本==2017-7-13 12:15:42
     * （动态模型模块导出模板功能）
     */
    @SuppressWarnings("resource")
    @Override
    public void templeExport(String modelId, HttpServletResponse resp) {
        try {
            OutputStream out = null;
            Map<String, String> mapCon = new HashMap<String, String>();
            Map<String, String> parm = new HashMap<String, String>();
            List<AttrConfig> configLst = null;
            List<AttrConfig> jspAttrLst = new ArrayList<AttrConfig>();
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            mapCon.put("tableTable", TableConst.TABLEPREFIX + modelId);
            mapCon.put("userId", user.getUserId() + "");
            parm.put("modelId", modelId);
            Model model = cacheUtil.getModel(modelId);

            //更改了导出模板，跟新增页面一致
            if (model.getIsMoreView() == 1) {//表示是多视图
                configLst = attrConfigDao.queryValidAttributeList(parm);
            } else {
                //根据modelid 和登录用户id查询当前用户拥有的属性权限
                configLst = attrConfigDao.queryAttributesListPermision(mapCon);
            }
            for (AttrConfig attrConfig : configLst) {
                //在新增页面展示，且不是编码格式
                if (attrConfig.getShowPage().contains("2") && !"4".equals(attrConfig.getModuleType())) { // 在新增页面展示
                    jspAttrLst.add(attrConfig);
                }
            }

            //第三种写法（刘晶写，从网上百度的一种导出大数据模板的方法）
            SXSSFWorkbook workbook = new SXSSFWorkbook(100); //创建新的Excel工作薄
            Sheet sheet = workbook.createSheet(modelId);    //创建本模型的工作表
            Row row = sheet.createRow(0); //在索引0的位置创建行（最顶端的行）
            sheet.setDefaultColumnWidth(30);//设置本sheet页,列的宽度

            CellStyle style = workbook.createCellStyle();//单元格的样式
            Font font = workbook.createFont();//设置字体颜色什么的
            font.setFontName("宋体");
            style.setFont(font);
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            //设置单元格的文本格式
            DataFormat format = workbook.createDataFormat();
            style.setDataFormat(format.getFormat("@"));

            for (int i = 0; i < jspAttrLst.size(); i++) {
                if (jspAttrLst.get(i).getIsNull() == 0) {//是否必填
                    CellStyle redStyle = workbook.createCellStyle();//单元格的样式
                    Font redfont = workbook.createFont();//设置字体颜色什么的
                    redfont.setFontName("宋体");
                    redfont.setColor(HSSFColor.RED.index);
                    redStyle.setFont(redfont);
                    redStyle.setAlignment(HorizontalAlignment.CENTER);
                    redStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                    sheet.setDefaultColumnStyle(i, style);//设置文本格式
                    ExcelUtil.addSXSSWorkCell(sheet, row, jspAttrLst.get(i).getAttrName(), i, redStyle, null);
                } else {
                    sheet.setDefaultColumnStyle(i, style);//设置文本格式
                    ExcelUtil.addSXSSWorkCell(sheet, row, jspAttrLst.get(i).getAttrName(), i, style, null);
                }
            }

            // 如果模型有主表，还要导出主表数据
            String mainId = model.getMaintableId();
            int isSub = model.getIsSubtable();//判断是否从表-1.是从表  0.是主表
            if (null != mainId && !"".equals(mainId) && isSub == 1) {//判断本模型是否从表
                Model mainModel = cacheUtil.getModel(mainId);
                ExcelUtil.addSXSSWorkCell(null, row, "主表ID", jspAttrLst.size(), style, null);
                Sheet mainSheet = workbook.createSheet(mainId);
                mainSheet.setDefaultColumnWidth(30);
                workbook.setSheetName(0, model.getModelName() + "(从表)");
                workbook.setSheetName(1, mainModel.getModelName() + "(主表)");
                Row mainRow = mainSheet.createRow(0);
                mainSheet.setDefaultColumnWidth(30);//设置本sheet页,列的宽度
                List<AttrConfig> mtfLst = new ArrayList<AttrConfig>();
                List<AttrConfig> mainConfigLst = cacheUtil.getAttrList(mainId);
                for (int m = 0; m < mainConfigLst.size(); m++) {
                    AttrConfig atf = mainConfigLst.get(m);
                    if (atf.getIsNull() == 0 && atf.getAttrType().equals("VARCHAR2")) {//表示必填
                        mtfLst.add(atf);
                    }
                }
                for (int i = 0; i < mtfLst.size(); i++) {
                    mainSheet.setDefaultColumnStyle(i, style);//设置文本格式
                    ExcelUtil.addSXSSWorkCell(mainSheet, mainRow, mtfLst.get(i).getAttrName(), i, style, null);
                }
                ExcelUtil.addSXSSWorkCell(mainSheet, mainRow, "主表主键(ID)", mtfLst.size(), style, null);
                //查询主表的数据写出到excel
                Map<String, String> cond = new HashMap<String, String>();
                AttrConfig ac = new AttrConfig();
                ac.setAttrName("主表主键(ID)");
                ac.setDataType("VARCHAR2");
                ac.setAttrColumn("id");
                mtfLst.add(ac);
                String columns = SystemAttributeFactory.getColumnByConfig(mtfLst);
                cond.put("columns", columns);
                cond.put("tableName", mainModel.getTableName());
                cond.put("state", "4");
                cond.put("status", "0");

                Map<String, Object> parmM = new HashMap<>();
                parmM.put("tableName", mainModel.getTableName());
                List<Map<String, Object>> mainLst = jspActionDao.queryList(cond);
                if (!mainLst.isEmpty()) {
                    for (int m = 0; m < mainLst.size(); m++) {
                        Row ContentRow = mainSheet.createRow(m + 1);
                        Map<String, Object> amap = mainLst.get(m);
                        String bus[] = columns.split(",");
                        for (int j = 0; j < bus.length; j++) {
                            Cell cell = ContentRow.createCell(j);
                            cell.setCellType(Cell.CELL_TYPE_STRING);//设置单元格格式为文本
                            String colu = bus[j];
                            String name = (String) amap.get(colu.toLowerCase());
                            if (name == "null" || name == "") {
                                cell.setCellValue("null");
                            } else {
                                cell.setCellValue(name);
                            }
                        }
                    }

                }
            } else {
                workbook.setSheetName(0, model.getModelName());
            }
            //对于这种模型之间的引用
            List<Model> moLst = new ArrayList<Model>();
            for (int i = 0; i < jspAttrLst.size(); i++) {
                AttrConfig uConfig = jspAttrLst.get(i);
                String type = uConfig.getAttrType();
                if ("radioType".equals(type) || "checkBoxType".equals(type)
                        || "selectList".equals(type) || "popList".equals(type) || "listTree".equals(type)) {
                    //由于popList弹出框这块，添加了一个外部引用的功能，是非动态模型的操作，所以，这块要过滤掉
                    if (!"5".equals(uConfig.getModuleType())) {//如果组件关系不是外部选择设置的话
                        Model sModel = cacheUtil.getModel(uConfig.getDataSourceTable());
//						if(!model.equals(sModel)){
                        //如果涉及到本模型相关的引用的话，也需要将数据导出来，做参考
                        moLst.add(sModel);
//						}
                    }
                }
            }
            List<Model> listWithoutDup = new ArrayList<Model>(new HashSet<Model>(moLst));
            for (int i = 0; i < listWithoutDup.size(); i++) {
                Model ramodel = listWithoutDup.get(i);
                List<AttrConfig> conLst = cacheUtil.getAttrList(ramodel.getId());
                //如果该模型引用了本模型，那么创建sheet页，需要更改sheet页名称
                String sheetName = ramodel.getModelName();
                if (ramodel.getModelName().equals(model.getModelName())) {
                    sheetName = sheetName + "引用";
                }
                Sheet raSheet = workbook.createSheet(sheetName);//创建主表的sheet
                raSheet.setDefaultColumnWidth(30);
                Row raRow = raSheet.createRow(0);
                for (int k = 0; k < conLst.size(); k++) {
                    raSheet.setDefaultColumnStyle(k, style);//设置文本格式
                    ExcelUtil.addSXSSWorkCell(raSheet, raRow, conLst.get(k).getAttrName(), k, style, null);
                }
                Map ramap = new HashMap();
                String busiCols = cacheUtil.getQueryColumns(ramodel.getId());
                ramap.put("columns", busiCols.substring(0, busiCols.length() - 1));
                ramap.put("tableName", ramodel.getTableName());
                ramap.put("state", "4");
                ramap.put("status", "0");
                String sqlcount = "select count(*) from  " + ramodel.getTableName();
                int dataNum = jdbcDao.executeSqlForCount(sqlcount);//返回来查询的结果
                if (dataNum <= 10000) {
                    List<Map<String, Object>> list = jspActionDao.queryList(ramap);

                    for (int m = 0; m < list.size(); m++) {
                        Row ContentRow = raSheet.createRow(m + 1);
                        Map<String, Object> amap = list.get(m);
                        String bus[] = busiCols.split(",");
                        for (int j = 0; j < bus.length; j++) {
                            Cell cell = ContentRow.createCell(j);
                            cell.setCellType(Cell.CELL_TYPE_STRING);//设置单元格格式为文本
                            String colu = bus[j];
                            String name = (String) amap.get(colu.toLowerCase());
                            if (name == "null" || name == "") {
                                cell.setCellValue("null");
                            } else {
                                cell.setCellValue(name);
                            }
                        }
                    }
                }
            }
            out = resp.getOutputStream();
            ExcelUtil.setSXSSWorkResponseHeader(resp, model.getModelName());
            workbook.write(out);
            workbook.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入
     */
    @Override
    public Map<String, Object> excelImport(String modelId, InputStream input) {
        Model model = cacheUtil.getModel(modelId);
        Map<String, Object> result_map = new HashMap<>();
        List<AttrConfig> configLst = null;
        List<AttrConfig> jspAttrLst = new ArrayList<AttrConfig>();
        boolean success = false;// 默认此次导入操作不成功
        //ExcelUtil eu=new ExcelUtil();

        Map<String, String> mapCon = new HashMap<String, String>();
        Map<String, String> parm = new HashMap<String, String>();
        parm.put("modelId", modelId);
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        //mapCon.put("modelId", modelId);
        mapCon.put("tableTable", TableConst.TABLEPREFIX + modelId);
        mapCon.put("userId", user.getUserId() + "");
        //mapCon.put("needOrder", "1");
        if (model.getIsMoreView() == 1) {//表示是多视图
            configLst = attrConfigDao.queryValidAttributeList(parm);
        } else {
            //根据modelid 和登录用户id查询当前用户拥有的属性权限
            configLst = attrConfigDao.queryAttributesListPermision(mapCon);
        }

        for (AttrConfig attrConfig : configLst) {
            //在新增页面展示，且不是编码格式
            if (attrConfig.getShowPage().contains("2") && !"4".equals(attrConfig.getModuleType())) { // 在新增页面展示
                jspAttrLst.add(attrConfig);
            }
        }
        List<Map<Integer, Map<String, String>>> attrValueLst = ExcelUtil.excelImport(modelId, input, jspAttrLst);   //返回的值和属性对应值的map集合
        if (attrValueLst.size() != 0) {
            //同批次导入数据校验
            Map<String, Object> checkResult = checkImport(attrValueLst, jspAttrLst);
            boolean flag = (boolean) checkResult.get("flag");
            if (flag) {
                //校验属性值
                result_map = check_sxz(attrValueLst, model, jspAttrLst);
                if ((Boolean) result_map.get("bool")) {
                    List<Map<Integer, Map<String, String>>> resultList = (List<Map<Integer, Map<String, String>>>) result_map.get("list");
                    //插入数据库
                    if (resultList.size() > 0) {
                        List<String> idLst = insert_sxz(model, resultList);
                        success = true;
                        //将数据id保存到集合里
                        result_map.put("idLst", idLst);
                    } else {
                        try {
                            String errText = "模板没有数据，请检查完，在操作！";
                            String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                            ExportUtil.errTxt(errText, fileName);
                            //eu.errTxt(errText, fileName);
                            result_map.put("err_fileName", fileName);
                            result_map.put("bool", success);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    try {
                        String errText = (String) result_map.get("error");
                        String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                        //eu.errTxt(errText, fileName);
                        ExportUtil.errTxt(errText, fileName);
                        result_map.put("err_fileName", fileName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                result_map.put("bool", success);
            } else {
                String errText = (String) checkResult.get("errorResult");
                String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                //eu.errTxt(errText, fileName);
                try {
                    ExportUtil.errTxt(errText, fileName);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                result_map.put("err_fileName", fileName);
                result_map.put("bool", flag);
            }

        } else {
            try {
                String errText = "模板没有数据，请检查完，在操作！";
                String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                ExportUtil.errTxt(errText, fileName);
                //eu.errTxt(errText, fileName);
                result_map.put("err_fileName", fileName);
                result_map.put("bool", success);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result_map;
    }
    /**
     * <p>TODO</p>
     * @param : @param modelId
     * @param : @param input
     * @param : @return
     * @author : xiaoliu
     * @date :2017年10月26日下午3:28:43
     */


    /**
     * <p>TODO 对应EXCEL收集数据进行逐条检验</p>
     * <p>@param attrValueLst
     * <p>@param model
     * <p>@param configAttrLst
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年11月1日下午4:58:20
     */
    private Map<String, Object> check_sxz(List<Map<Integer, Map<String, String>>> attrValueLst, Model model, List<AttrConfig> jspAttrLst) {
        Map<String, Object> result_map = new HashMap<>();
        List<Map<Integer, Map<String, String>>> rst = new ArrayList<Map<Integer, Map<String, String>>>();
        boolean bool = true;
        StringBuffer sb = new StringBuffer();
        Map mapCon = new HashMap();
        Map parm = new HashMap();
        parm.put("modelId", model.getId());
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        mapCon.put("tableTable", model.getTableName());
        mapCon.put("userId", user.getUserId() + "");

        for (int i = 0; i < attrValueLst.size(); i++) {
            Map<Integer, Map<String, String>> map = attrValueLst.get(i);//获取到sheet页的所有行数据
            for (int j = 2; j <= map.size(); j++) {
                Map<String, String> rowMap = map.get(j);
                Map<Integer, Map<String, String>> resMap = new HashMap<Integer, Map<String, String>>();
                Map<String, String> rowMapHh = new HashMap<String, String>();
                String rowMapH = "";
                for (int k = 0; k < jspAttrLst.size(); k++) {
                    AttrConfig attrConfig = jspAttrLst.get(k);//在新增页面有效的数据列
                    Map<String, Object> cellMap = new HashMap<>();
                    cellMap = check_Column(model, attrConfig, j - 1, rowMap);
                    rowMapH = (String) cellMap.get("attrValue");
                    rowMapHh.put(attrConfig.getAttrColumn().toUpperCase(), rowMapH);
                    if (!(boolean) cellMap.get("bool")) {
                        bool = false;
                        sb.append((String) cellMap.get("err"));
                    }
                }
                if (bool) {
                    rowMapHh.put("tableName", model.getTableName());
                    rowMapHh.put("modelId", model.getId());
                    resMap.put(j, rowMapHh);
                    rst.add(resMap);
                }
            }
        }
        result_map.put("error", sb.toString());
        result_map.put("bool", bool);
        result_map.put("list", rst);
        return result_map;
    }

    /**
     * <p>TODO 校验数据针对多视图</p>
     * <p>@param attrValueLst
     * <p>@param model
     * <p>@param jspAttrLst
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年11月1日下午5:05:10
     */
    private Map<String, Object> checkDataLst(Map<Integer, Map<String, String>> dataMap, Model model, List<AttrConfig> jspAttrLst) {
        Map<String, Object> returnMap = new HashMap<>();
        List<Map<String, Object>> dataLst = new ArrayList<Map<String, Object>>();//校验通过的行数
        boolean bool = true;
        StringBuffer sb = new StringBuffer();
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        Map mapCon = new HashMap();
        Map parm = new HashMap();
        parm.put("modelId", model.getId());
        mapCon.put("tableTable", model.getTableName());
        mapCon.put("userId", user.getUserId() + "");
        //现在调试这块要好好注意下
        for (int j = 1; j <= dataMap.size(); j++) {//从第二行开始才是有效的数据
            Map<String, String> dataRowMap = dataMap.get(j);//具体到某一行的数据
            Map<Integer, Map<String, Object>> rowCheckMap = this.checkRowDate(model, jspAttrLst, j, dataRowMap);
            //rowMap 首先传递回来，本次操作的这行数据校验是通过还是失败，还有 及（关联关系，级联关系和那个是否多视图返回来的值（关联值））
            //开始解析校验返回来的这行数据
            Map<String, Object> setRowMap = rowCheckMap.get(j);//获取返回来的这行的校验的数据
            boolean flag = (boolean) setRowMap.get("flag");

            if (!flag) {//如果校验未通过
                String erstr = (String) setRowMap.get("errStr");
                sb.append(erstr);//将错误信息收集起来
            }
            dataLst.add(setRowMap);
        }

        if (StringUtils.isEmpty(sb.toString())) {//判断错误原因是不是为空
            returnMap.put("bool", bool);
        } else {
            bool = false;
            returnMap.put("bool", bool);
        }
        returnMap.put("error", sb.toString());
        returnMap.put("dataLst", dataLst);
        return returnMap;
    }

    private Map<Integer, String> getTableSeq(Map<Integer, Map<String, String>> map, Model model) {
        Map<Integer, String> result_map = new HashMap<Integer, String>();
        Map<String, String> cond = new HashMap<String, String>();
        cond.put("tableSeqNextval", model.getTableName() + "_SEQ.nextval");
        for (int i = 2; i <= map.size(); i++) {
            String id = jspActionDao.selectIdBySeq(cond);
            result_map.put(i, id);
        }
        return result_map;
    }

    /**
     * <p>TODO 多视图数据，按照行数去进行校验</p>
     * <p>@param model
     * <p>@param jspAttrLst
     * <p>@param j
     * <p>@param rowMap
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年11月30日上午11:30:52
     */
    private Map<Integer, Map<String, Object>> checkRowDate(Model model, List<AttrConfig> jspAttrLst, int j, Map<String, String> rowMap) {
        Map<Integer, Map<String, Object>> rowCheckMap = new HashMap<Integer, Map<String, Object>>();//定义一个行返回集合
        Map<String, Object> cellMap = new HashMap<>();
        List<AttrConfig> baseAttrLst = new ArrayList<AttrConfig>();
        boolean flag = true;//定义一个校验结果（具体到某一行的校验）
        StringBuffer errstr = new StringBuffer();//定义一个错误原因的结果集，也是针对行
        //从这里分成两股方法判断
        /*第一步，获取基本视图里面的数据校验基本视图*/
        for (AttrConfig conf : jspAttrLst) {
            if (StringUtils.isEmpty(conf.getGroupId())) {//属性组ID为空
                baseAttrLst.add(conf);
            }
        }
        //校验基本视图里面的数据
        if (!CollectionUtils.isEmpty(baseAttrLst)) {
            for (AttrConfig base : baseAttrLst) {//循环属性列
                String atrName = base.getAttrName();//属性名称
                String mxL = base.getAttrLength(); // 长度
                String atrType = base.getAttrType();//属性类型
                int snul = base.getIsNull();//是否为空
                String col = base.getAttrColumn().toLowerCase();//列名
                String colVal = rowMap.get(col);//输入的值（Excel里面存储的结果集）

                if (!StringUtils.isEmpty(colVal)) {//如果Excel文件里面存储的这列的值不为空
                    if (atrType.equals("NUMBERM")) {//首先判断小数类型 NUMBERM-小数类型
                        int zs = base.getAttrZs();// 获取整数位长度
                        int xs = base.getAttrXs();// 获取小数位长度
                        String xLen = (zs + 1 + xs) + "";// (小数的数据长度限制)
                        if (colVal.indexOf(".") != -1) {//包含
                            if (Integer.parseInt(xLen) < colVal.length()) {
                                errstr.append("第" + (j) + "行【" + atrName + "】总长度不能超过" + Integer.parseInt(xLen) + "！\r\n");
                                flag = false;
                            } else {
                                String qD = colVal.substring(0, colVal.indexOf("."));//获取“.之前的数据”
                                String hD = colVal.substring(colVal.indexOf(".") + 1);//获取“.之后的数据”
                                if (zs < qD.length()) {
                                    errstr.append("第 " + (j) + "行【" + atrName + "】整数位长度不能超过" + zs + "！\r\n");
                                    flag = false;
                                }
                                if (xs < hD.length()) {
                                    if (xs < hD.length()) {
                                        errstr.append("第 " + (j) + "行【" + atrName + "】小数位长度不能超过" + xs + "！\r\n");
                                        flag = false;
                                    }
                                }
                            }
                        } else {//不包含(说明是整数,整数的长度是不能超过属性设置中小数位的整数位长度的)
                            if (zs < colVal.length()) {
                                errstr.append("第" + (j) + "行【" + atrName + "】整数位长度不能超过" + zs + "！\r\n");
                                flag = false;
                            }
                        }
                    } else if (atrType.equals("NUMBER")) {//NUMBER-数字类型
                        if (!StringUtils.isEmpty(mxL)) {
                            Pattern pattern = Pattern.compile("[1-9]+[0-9]*");
                            Matcher isNum = pattern.matcher(colVal);
                            if (!isNum.matches()) {
                                errstr.append("第" + (j) + "行【" + atrName + "】只能填写纯数字 \r\n");
                                flag = false;
                            }
                        } else {
                            if (Integer.parseInt(mxL) < atrName.length()) {
                                errstr.append("第 " + (j) + "行【" + atrName + "】长度不能超过" + Integer.parseInt(mxL) + "！\r\n");
                                flag = false;
                            }
                        }
                    } else if ("DATE".equals(atrType)) {//DATE-日期类型
                        Pattern pattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
                        Matcher isNum = pattern.matcher(colVal);
                        if (!isNum.matches()) {
                            errstr.append("第" + (j) + "行【" + atrName + "】日期格式不正确(例如： 1993-06-18 12:23:34)！请重新检查。。。 \r\n");
                            flag = false;
                        }
                    } else if ("selectList".equals(atrType) || "popList".equals(atrType)
                            || "radioType".equals(atrType)) {//selectList 下拉框,popList 弹出框,//radioType 单选框
                        //modutype 1(关联关系),2(级联关系),3(选择设置),5(外部数据来源)
                        if ("5".equals(base.getModuleType())) {//外部数据来源	//要判断用户输入的物料编码是否正确
                            String wTable = base.getTabNoName();    //获取到用户输入的表名
                            String wColumns = base.getDataSourceColumn();//获取到那个属性设置选择的属性列
                            String wColumn = "";
                            if (wColumns.indexOf(",") != -1) {//包含逗号
                                wColumn = wColumns.split(",")[0];
                            } else {
                                wColumn = wColumns;
                            }
                            Map map = new HashMap();
                            map.put("columns", wColumn);
                            map.put("tableName", wTable);
                            map.put("where", "t." + wColumn + "='" + colVal + "' and t.state = 4 ");
                            List<Map<String, Object>> datLst = jspActionDao.queryList(map);//获取到的结果集
                            if (datLst.size() > 0) {
                                Map<String, Object> dataMap = datLst.get(0);
                                String idValue = (String) dataMap.get(wColumn);
                                if (!StringUtils.isEmpty(idValue)) {
                                    colVal = idValue;
                                } else {
                                    errstr.append("第 " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                    flag = false;
                                }
                            } else {
                                errstr.append("第" + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                flag = false;
                            }
                        } else {//1(关联关系),2(级联关系),3(选择设置)
                            String dsTable = base.getDataSourceTable().trim();
                            if (dsTable != null && !dsTable.isEmpty()) {
                                Model modelds = cacheUtil.getModel(dsTable);
                                //String dsColum=base.getDataSourceColumn();
                                //页面展示列
                                String pageShow = base.getDataSourceShowColumn();
                                Map<String, String> cond = new HashMap<String, String>();
                                cond.put("caseColumn", "");
                                cond.put("sourceTable", modelds.getTableName());
                                //cond.put("sourceCol", dsColum.replace(",", "||'_'||"));
                                cond.put("sourceCol", pageShow);
                                //String selectAttrId=base.getSelectedConfigAttr();
                                String caseForeignKey = base.getCascadedForeignKey();
                                String ModuleType = base.getModuleType();
                                if ("1".equals(ModuleType)) {//关联设置类型
                                    String Id = getdsTableIdbyColum(cond, ModuleType).get(colVal);
//										System.out.println(Id);
                                    if (!StringUtils.isEmpty(Id)) {
                                        colVal = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                    } else {
                                        flag = false;
                                        errstr.append("第" + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                    }
                                } else if ("2".equals(ModuleType) && null != caseForeignKey) {
                                    //级联设置型数据，判断作为级联条件的属性值是否存在属性来源表里
                                    AttrConfig caseAttrConfig = cacheUtil.getAttrConfig(dsTable, caseForeignKey);
                                    //String sourceCol = dsColum+","+caseAttrConfig.getAttrColumn();
                                    cond.put("sourceCol", pageShow);
                                    //String pageShow =
                                    cond.put("conditionCol", caseAttrConfig.getAttrColumn());
                                    cond.put("columnValue", rowMap.get(caseAttrConfig.getAttrColumn()));
                                    String Id = getdsTableIdbyColum(cond, ModuleType).get(colVal);
                                    if (!StringUtils.isEmpty(Id)) {
                                        colVal = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                    } else {
                                        flag = false;
                                        errstr.append("第" + (j) + "行级联条件【" + atrName + "】的值不在属性来源表!\r\n");
                                    }
                                } else if ("3".equals(ModuleType)) {//&& null != selectAttrId
                                    String Id = getdsTableIdbyColum(cond, ModuleType).get(colVal);
//										System.out.println(Id);
                                    if (!StringUtils.isEmpty(Id)) {
                                        colVal = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                    } else {
                                        flag = false;
                                        errstr.append("第" + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                    }
//										 //选择设置型数据，把设置要隐藏的属性的值置空
//										 String selectedStr=base.getSelectedConfigAttr();  //获取关联的列的值字符串
//										 String[] splitStr= selectedStr.split("@@");  // 1000:C_004@@1001:C_006,C_005
//							   			 for(int m=0;m<splitStr.length;m++){
//							   				 String[] splitId=splitStr[m].split(":");  //将id和关联的列拆分1  C_007  4 C_007,C_008
//							   				 if(!splitId[0].equals(colVal)){ //拆分后是4 C_007,C_008
//							   					 if(splitId[1].contains(",")){
//							   						 String[] str=splitId[1].split(",");
//							   						   for (int l = 0; l < str.length; l++) {
//							   							  cellMap.put(str[l], null);
//													   }
//							   					 }else{
//							   						 cellMap.put(splitId[1], null); //拆分后是1  C_007
//							   					 }
//							   				 }
//							   			 }
                                }
                            }
                        }
                    } else if ("listTree".equals(atrType)) {//listTree 列表树
                        String dsTable = base.getDataSourceTable();
                        String columnV = base.getDataSourceShowColumn();
                        if (null != dsTable && !"".equals(dsTable)) {
                            Map map = new HashMap();
                            map.put("columns", "t.ID");
                            map.put("tableName", "T_" + dsTable);
                            map.put("where", "t." + columnV + "='" + colVal + "' and t.state = 4 ");
                            List<Map<String, Object>> datLst = jspActionDao.queryList(map);
                            if (datLst.size() > 0) {
                                Map<String, Object> dataMap = datLst.get(0);
                                String idValue = (String) dataMap.get("id");
                                if (!StringUtils.isEmpty(idValue)) {
                                    colVal = idValue;
                                } else {
                                    flag = false;
                                    errstr.append("第 " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                }
                            } else {
                                flag = false;
                                errstr.append("第" + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                            }
                        }
                    } else if ("checkBoxType".equals(atrType)) {//checkBoxType 复选框
                        String dsTable = base.getDataSourceTable().trim();
                        if (dsTable != null && !dsTable.isEmpty()) {
                            Model modelds = cacheUtil.getModel(dsTable);
                            //String dsColum=base.getDataSourceColumn();
                            Map<String, String> cond = new HashMap<String, String>();
                            cond.put("caseColumn", "");
                            cond.put("sourceTable", modelds.getTableName());
                            //cond.put("sourceCol", dsColum.replace(",", "||'_'||"));
                            cond.put("sourceCol", base.getDataSourceShowColumn());
                            String ModuleType = base.getModuleType();
                            //判断复选框的模型中间是否有逗号隔开（即复选框是否选择了多个值）
                            if (colVal.indexOf(",") != -1) {//包含逗号
                                String ids = "";
                                for (String str : colVal.split(",")) {//一个个的去解析这个值
                                    String Id = getdsTableIdbyColum(cond, ModuleType).get(str);
                                    if (!Id.isEmpty() && Id != null && !"".equals(Id) && Id != "null") {
                                        ids = ids + Id + ",";
                                    } else {
                                        flag = false;
                                        errstr.append("第 " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                    }
                                }
                                if (!StringUtils.isEmpty(ids)) {
                                    ids = ids.trim();
                                    colVal = ids.substring(0, ids.trim().length() - 1);//将查询到的值，赋给当前输入值，保存到数据库
                                }
                            } else {
                                String Id = getdsTableIdbyColum(cond, ModuleType).get(colVal);
                                if (!StringUtils.isEmpty(Id)) {
                                    colVal = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                    //rowMap.put(col, Id);
                                } else {
                                    flag = false;
                                    errstr.append("第 " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                }
                            }
                        }
                    } else if ("VARCHAR2".equals(atrType)) {//VARCHAR2  字符串
                        String ruleType = base.getRuleType();//获取规则类型
                        if (!StringUtils.isEmpty(ruleType)) {
                            String ruleId = base.getRuleTypeId();//规则校验id
                            if (ruleType.equals("0")) {//表示是校验唯一
                                //拿到当前这个值，去跟数据库里面的这个值去比较，判断是否重复
                                Map map = new HashMap();
                                map.put("columns", col);
                                map.put("tableName", model.getTableName());
                                String where = "t." + col + "='" + colVal + "' and t.state =4 ";
                                map.put("where", where);
                                List<Map<String, Object>> dataLst = jspActionDao.queryList(map);
                                if (dataLst.size() > 0) {
                                    errstr.append("第 " + (j) + "行【" + atrName + "】的值已存在,唯一性校验失败!\r\n");
                                }
                            } else if (ruleType.equals("1")) {//表示校验电子邮件
                                if (!StringUtils.isEmpty(ruleId)) {
                                    CheckRule checkRule = checkRuleDao.getById(ruleId);
                                    String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                    checkRuleExpress = checkRuleExpress.replace("\\", "");
                                    // String  checkRuleExpress = "^(w)+(.w+)*@(w)+((.w{2,3}){1,3})$";//正则表达式
                                    Pattern p = Pattern.compile(checkRuleExpress);
                                    Matcher m = p.matcher(colVal);
                                    if (!m.matches()) {
                                        flag = false;
                                        errstr.append("第" + (j) + "行【" + atrName + "】不符合邮箱的填写格式!\r\n");
                                    }
                                }
                            } else if (ruleType.equals("2")) {//表示校验手机号码
                                if (!StringUtils.isEmpty(ruleId)) {
                                    CheckRule checkRule = checkRuleDao.getById(ruleId);
                                    String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                    checkRuleExpress = checkRuleExpress.replace("\\", "");
                                    Pattern p = Pattern.compile(checkRuleExpress);
                                    Matcher m = p.matcher(colVal);
                                    if (!m.matches()) {
                                        flag = false;
                                        errstr.append("第 " + (j) + "行【" + atrName + "】不符合手机号码的填写格式!\r\n");
                                    }
                                }
                            } else if (ruleType.equals("3")) {//表示校验座机号码
                                if (!StringUtils.isEmpty(ruleId)) {
                                    CheckRule checkRule = checkRuleDao.getById(ruleId);
                                    String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                    Pattern p = Pattern.compile(checkRuleExpress);
                                    checkRuleExpress = checkRuleExpress.replace("\\", "");
                                    Matcher m = p.matcher(colVal);
                                    if (!m.matches()) {
                                        flag = false;
                                        errstr.append("第" + (j) + "行【" + atrName + "】不符合座机号的填写格式!\r\n");
                                    }
                                }
                            } else if (ruleType.equals("4")) {//表示校验邮政编码
                                if (!StringUtils.isEmpty(ruleId)) {
                                    CheckRule checkRule = checkRuleDao.getById(ruleId);
                                    String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                    checkRuleExpress = checkRuleExpress.replace("\\", "");
                                    Pattern p = Pattern.compile(checkRuleExpress);
                                    Matcher m = p.matcher(colVal);
                                    if (!m.matches()) {
                                        flag = false;
                                        errstr.append("第" + (j) + "行【" + atrName + "】不符合邮编的填写格式!\r\n");
                                    }
                                }
                            }
                        }
                    }
                } else {//说明Excel文档里面这列值为空  //然后判断这个属性列在属性设置里面是否为空
                    if (snul == 0) {//如果是必填项
                        errstr.append("第 " + (j) + "行【" + atrName + "】是必填项！\r\n");
                        flag = false;
                    }
                }
                cellMap.put(col, colVal);
            }
        }
        /*第二步，获取视图设置里面的视图里面的数据校验自定义视图*/

        List<AttrGroup> groupLst = attrGroupDao.queryGroupByModelId(model.getId());//获取属性组集合
        if (!CollectionUtils.isEmpty(groupLst)) {
            for (AttrGroup group : groupLst) {
                String groupId = group.getId();
                List<AttrConfig> alst = cacheUtil.getAttrListByGroup(model.getId(), groupId);

                if (!CollectionUtils.isEmpty(alst)) {
                    boolean rowflag = true;
                    for (AttrConfig conf : alst) {
                        String col = conf.getAttrColumn().toLowerCase();
                        String colVal = (String) rowMap.get(col);
                        if (!StringUtils.isEmpty(colVal)) {//判断它为空，如果都为空，就说明没有选中
                            rowflag = false;
                        }
                    }

                    if (!rowflag) {//表示选中啦，要走校验逻辑
                        for (AttrConfig attr : alst) {//循环属性列
//								   boolean flag=true;//定义一个校验结果（具体到某一行的校验）
//								   StringBuffer errstr=new StringBuffer();//定义一个错误原因的结果集，也是针对行
                            String atrName = attr.getAttrName();//属性名称
                            String mxL = attr.getAttrLength(); // 长度
                            String atrType = attr.getAttrType();//属性类型
                            int snul = attr.getIsNull();//是否为空
                            String col = attr.getAttrColumn().toLowerCase();//列名
                            String colVal = rowMap.get(col);//输入的值（Excel里面存储的结果集）

                            if (!StringUtils.isEmpty(colVal)) {//如果Excel文件里面存储的这列的值不为空
                                if (atrType.equals("NUMBERM")) {//首先判断小数类型 NUMBERM-小数类型
                                    int zs = attr.getAttrZs();// 获取整数位长度
                                    int xs = attr.getAttrXs();// 获取小数位长度
                                    String xLen = (zs + 1 + xs) + "";// (小数的数据长度限制)
                                    if (colVal.indexOf(".") != -1) {//包含
                                        if (Integer.parseInt(xLen) < colVal.length()) {
                                            errstr.append("第 " + (j) + "行【" + atrName + "】总长度不能超过" + Integer.parseInt(xLen) + "！\r\n");
                                            flag = false;
                                        } else {
                                            String qD = colVal.substring(0, colVal.indexOf("."));//获取“.之前的数据”
                                            String hD = colVal.substring(colVal.indexOf(".") + 1);//获取“.之后的数据”
                                            if (zs < qD.length()) {
                                                errstr.append("第 " + (j) + "行【" + atrName + "】整数位长度不能超过" + zs + "！\r\n");
                                                flag = false;
                                            }
                                            if (xs < hD.length()) {
                                                if (xs < hD.length()) {
                                                    errstr.append("第 " + (j) + "行【" + atrName + "】小数位长度不能超过" + xs + "！\r\n");
                                                    flag = false;
                                                }
                                            }
                                        }
                                    } else {//不包含(说明是整数,整数的长度是不能超过属性设置中小数位的整数位长度的)
                                        if (zs < colVal.length()) {
                                            errstr.append("第 " + (j) + "行【" + atrName + "】整数位长度不能超过" + zs + "！\r\n");
                                            flag = false;
                                        }
                                    }
                                } else if (atrType.equals("NUMBER")) {//NUMBER-数字类型
                                    if (!StringUtils.isEmpty(mxL)) {
                                        Pattern pattern = Pattern.compile("[1-9]+[0-9]*");
                                        Matcher isNum = pattern.matcher(colVal);
                                        if (!isNum.matches()) {
                                            errstr.append("第 " + (j) + "行【" + atrName + "】只能填写纯数字 \r\n");
                                            flag = false;
                                        }
                                    } else {
                                        if (Integer.parseInt(mxL) < atrName.length()) {
                                            errstr.append("第 " + (j) + "行【" + atrName + "】长度不能超过" + Integer.parseInt(mxL) + "！\r\n");
                                            flag = false;
                                        }
                                    }
                                } else if ("DATE".equals(atrType)) {//DATE-日期类型
                                    Pattern pattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
                                    Matcher isNum = pattern.matcher(colVal);
                                    if (!isNum.matches()) {
                                        errstr.append("第  " + (j) + "行【" + atrName + "】日期格式不正确(例如： 1993-06-18 12:23:34)！请重新检查。。。 \r\n");
                                        flag = false;
                                    }
                                } else if ("selectList".equals(atrType) || "popList".equals(atrType)
                                        || "radioType".equals(atrType)) {//selectList 下拉框,popList 弹出框,//radioType 单选框
                                    //modutype 1(关联关系),2(级联关系),3(选择设置),5(外部数据来源)
                                    if ("5".equals(attr.getModuleType())) {//外部数据来源	//要判断用户输入的物料编码是否正确
                                        String wTable = attr.getTabNoName();    //获取到用户输入的表名
                                        String wColumns = attr.getDataSourceColumn();//获取到那个属性设置选择的属性列
                                        String wColumn = "";
                                        if (wColumns.indexOf(",") != -1) {//包含逗号
                                            wColumn = wColumns.split(",")[0];
                                        } else {
                                            wColumn = wColumns;
                                        }
                                        Map map = new HashMap();
                                        map.put("columns", wColumn);
                                        map.put("tableName", wTable);
                                        map.put("where", "t." + wColumn + "='" + colVal + "' and t.state = 4 ");
                                        List<Map<String, Object>> datLst = jspActionDao.queryList(map);//获取到的结果集
                                        if (datLst.size() > 0) {
                                            Map<String, Object> dataMap = datLst.get(0);
                                            String idValue = (String) dataMap.get(wColumn);
                                            if (!StringUtils.isEmpty(idValue)) {
                                                colVal = idValue;
                                            } else {
                                                errstr.append("第  " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                                flag = false;
                                            }
                                        } else {
                                            errstr.append("第  " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                            flag = false;
                                        }
                                    } else {//1(关联关系),2(级联关系),3(选择设置)
                                        String dsTable = attr.getDataSourceTable().trim();
                                        if (dsTable != null && !dsTable.isEmpty()) {
                                            Model modelds = cacheUtil.getModel(dsTable);
                                            //String dsColum=attr.getDataSourceColumn();
                                            String pageShow = attr.getDataSourceShowColumn();//获取页面展示列
                                            Map<String, String> cond = new HashMap<String, String>();
                                            cond.put("caseColumn", "");
                                            cond.put("sourceTable", modelds.getTableName());
                                            //cond.put("sourceCol", dsColum.replace(",", "||'_'||"));
                                            cond.put("sourceCol", pageShow);
                                            //String selectAttrId=attr.getSelectedConfigAttr();
                                            String caseForeignKey = attr.getCascadedForeignKey();
                                            String ModuleType = attr.getModuleType();
                                            if ("1".equals(ModuleType)) {//关联设置类型
                                                String Id = getdsTableIdbyColum(cond, ModuleType).get(colVal);
//														System.out.println(Id);
                                                if (!StringUtils.isEmpty(Id)) {
                                                    colVal = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                                } else {
                                                    flag = false;
                                                    errstr.append("第 " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                                }
                                            } else if ("2".equals(ModuleType) && null != caseForeignKey) {
                                                //级联设置型数据，判断作为级联条件的属性值是否存在属性来源表里
                                                AttrConfig caseAttrConfig = cacheUtil.getAttrConfig(dsTable, caseForeignKey);
                                                //String sourceCol = dsColum+","+caseAttrConfig.getAttrColumn();
                                                //cond.put("sourceCol", sourceCol.replace(",", "||'_'||"));
                                                cond.put("sourceCol", pageShow);
                                                cond.put("conditionCol", caseAttrConfig.getAttrColumn());
                                                cond.put("columnValue", rowMap.get(caseAttrConfig.getAttrColumn()));
                                                String Id = getdsTableIdbyColum(cond, ModuleType).get(colVal);
                                                if (!StringUtils.isEmpty(Id)) {
                                                    colVal = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                                } else {
                                                    flag = false;
                                                    errstr.append("第  " + (j) + "行级联条件【" + atrName + "】的值不在属性来源表!\r\n");
                                                }
                                            } else if ("3".equals(ModuleType)) {//&& null != selectAttrId
                                                String Id = getdsTableIdbyColum(cond, ModuleType).get(colVal);
//														System.out.println(Id);
                                                if (!StringUtils.isEmpty(Id)) {
                                                    colVal = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                                } else {
                                                    flag = false;
                                                    errstr.append("第" + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                                }

//														 //选择设置型数据，把设置要隐藏的属性的值置空
//														 String selectedStr=attr.getSelectedConfigAttr();  //获取关联的列的值字符串
//														 String[] splitStr= selectedStr.split("@@");  // 1000:C_004@@1001:C_006,C_005
//											   			 for(int m=0;m<splitStr.length;m++){
//											   				 String[] splitId=splitStr[m].split(":");  //将id和关联的列拆分1  C_007  4 C_007,C_008
//											   				 if(!splitId[0].equals(colVal)){ //拆分后是4 C_007,C_008
//											   					 if(splitId[1].contains(",")){
//											   						 String[] str=splitId[1].split(",");
//											   						   for (int l = 0; l < str.length; l++) {
//											   							  cellMap.put(str[l], null);
//																	   }
//											   					 }else{
//											   						 cellMap.put(splitId[1], null); //拆分后是1  C_007
//											   					 }
//											   				 }
//											   			 }
                                            }
                                        }
                                    }
                                } else if ("listTree".equals(atrType)) {//listTree 列表树
                                    String dsTable = attr.getDataSourceTable();
                                    String columnV = attr.getDataSourceShowColumn();
                                    if (null != dsTable && !"".equals(dsTable)) {
                                        Map map = new HashMap();
                                        map.put("columns", "t.ID");
                                        map.put("tableName", "T_" + dsTable);
                                        map.put("where", "t." + columnV + "='" + colVal + "' and t.state = 4 ");
                                        List<Map<String, Object>> datLst = jspActionDao.queryList(map);
                                        if (datLst.size() > 0) {
                                            Map<String, Object> dataMap = datLst.get(0);
                                            String idValue = (String) dataMap.get("id");
                                            if (!StringUtils.isEmpty(idValue)) {
                                                colVal = idValue;
                                            } else {
                                                flag = false;
                                                errstr.append("第  " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                            }
                                        } else {
                                            flag = false;
                                            errstr.append("第  " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                        }
                                    }
                                } else if ("checkBoxType".equals(atrType)) {//checkBoxType 复选框
                                    String dsTable = attr.getDataSourceTable().trim();
                                    if (dsTable != null && !dsTable.isEmpty()) {
                                        Model modelds = cacheUtil.getModel(dsTable);
                                        //String dsColum=attr.getDataSourceColumn();
                                        Map<String, String> cond = new HashMap<String, String>();
                                        cond.put("caseColumn", "");
                                        cond.put("sourceTable", modelds.getTableName());
                                        cond.put("sourceCol", attr.getDataSourceShowColumn());
                                        String ModuleType = attr.getModuleType();
                                        //判断复选框的模型中间是否有逗号隔开（即复选框是否选择了多个值）
                                        if (colVal.indexOf(",") != -1) {//包含逗号
                                            String ids = "";
                                            for (String str : colVal.split(",")) {//一个个的去解析这个值
                                                String Id = getdsTableIdbyColum(cond, ModuleType).get(str);
                                                if (!Id.isEmpty() && Id != null && !"".equals(Id) && Id != "null") {
                                                    ids = ids + Id + ",";
                                                } else {
                                                    flag = false;
                                                    errstr.append("第 " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                                }
                                            }
                                            if (!StringUtils.isEmpty(ids)) {
                                                ids = ids.trim();
                                                colVal = ids.substring(0, ids.trim().length() - 1);//将查询到的值，赋给当前输入值，保存到数据库
                                            }
                                        } else {
                                            String Id = getdsTableIdbyColum(cond, ModuleType).get(colVal);
                                            if (!StringUtils.isEmpty(Id)) {
                                                colVal = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                                //rowMap.put(col, Id);
                                            } else {
                                                flag = false;
                                                errstr.append("第 " + (j) + "行【" + atrName + "】的值不在其属性来源表!\r\n");
                                            }
                                        }
                                    }
                                } else if ("VARCHAR2".equals(atrType)) {//VARCHAR2  字符串
                                    String ruleType = attr.getRuleType();//获取规则类型
                                    if (!StringUtils.isEmpty(ruleType)) {
                                        String ruleId = attr.getRuleTypeId();//规则校验id
                                        if (ruleType.equals("0")) {//表示是校验唯一
                                            //拿到当前这个值，去跟数据库里面的这个值去比较，判断是否重复
                                            Map map = new HashMap();
                                            map.put("columns", col);
                                            map.put("tableName", model.getTableName());
                                            String where = "t." + col + "='" + colVal + "' and t.state =4 ";
                                            map.put("where", where);
                                            List<Map<String, Object>> dataLst = jspActionDao.queryList(map);
                                            if (dataLst.size() > 0) {
                                                errstr.append("第 " + (j) + "行【" + atrName + "】的值已存在,唯一性校验失败!\r\n");
                                            }
                                        } else if (ruleType.equals("1")) {//表示校验电子邮件
                                            if (!StringUtils.isEmpty(ruleId)) {
                                                CheckRule checkRule = checkRuleDao.getById(ruleId);
                                                String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                                checkRuleExpress = checkRuleExpress.replace("\\", "");
                                                //String  checkRuleExpress = "^(w)+(.w+)*@(w)+((.w{2,3}){1,3})$";//正则表达式
                                                Pattern p = Pattern.compile(checkRuleExpress);
                                                Matcher m = p.matcher(colVal);
                                                if (!m.matches()) {
                                                    flag = false;
                                                    errstr.append("第 " + (j) + "行【" + atrName + "】不符合邮箱的填写格式!\r\n");
                                                }
                                            }
                                        } else if (ruleType.equals("2")) {//表示校验手机号码
                                            if (!StringUtils.isEmpty(ruleId)) {
                                                CheckRule checkRule = checkRuleDao.getById(ruleId);
                                                String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                                checkRuleExpress = checkRuleExpress.replace("\\", "");
                                                Pattern p = Pattern.compile(checkRuleExpress);
                                                Matcher m = p.matcher(colVal);
                                                if (!m.matches()) {
                                                    flag = false;
                                                    errstr.append("第 " + (j) + "行【" + atrName + "】不符合手机号码的填写格式!\r\n");
                                                }
                                            }
                                        } else if (ruleType.equals("3")) {//表示校验座机号码
                                            if (!StringUtils.isEmpty(ruleId)) {
                                                CheckRule checkRule = checkRuleDao.getById(ruleId);
                                                String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                                checkRuleExpress = checkRuleExpress.replace("\\", "");
                                                Pattern p = Pattern.compile(checkRuleExpress);
                                                Matcher m = p.matcher(colVal);
                                                if (!m.matches()) {
                                                    flag = false;
                                                    errstr.append("第 " + (j) + "行【" + atrName + "】不符合座机号的填写格式!\r\n");
                                                }
                                            }
                                        } else if (ruleType.equals("4")) {//表示校验邮政编码
                                            if (!StringUtils.isEmpty(ruleId)) {
                                                CheckRule checkRule = checkRuleDao.getById(ruleId);
                                                String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                                checkRuleExpress = checkRuleExpress.replace("\\", "");
                                                Pattern p = Pattern.compile(checkRuleExpress);
                                                Matcher m = p.matcher(colVal);
                                                if (!m.matches()) {
                                                    flag = false;
                                                    errstr.append("第  " + (j) + "行 【" + atrName + "】不符合邮编的填写格式!\r\n");
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {//说明Excel文档里面这列值为空  //然后判断这个属性列在属性设置里面是否为空
                                if (snul == 0) {//如果是必填项
                                    errstr.append("第 " + (j) + "行【" + atrName + "】是必填项！\r\n");
                                    flag = false;
                                }
                            }
//								        cellMap.put("flag", flag);
//								        cellMap.put("errStr", errstr.toString());
                            cellMap.put(col, colVal);
//								      rowCheckMap.put(j, cellMap);
                        }

                    }
                }
            }

        }

        cellMap.put("flag", flag);
        cellMap.put("errStr", errstr.toString());
        rowCheckMap.put(j, cellMap);
        return rowCheckMap;
    }


    private Map<String, Object> check_Column(Model model, AttrConfig attrConfig, int j, Map<String, String> rowMap) {
        Map<String, Object> resMap = new HashMap<>();
        boolean bool = true;
        StringBuffer sb = new StringBuffer();
        String column = attrConfig.getAttrColumn().toLowerCase();//列名
        String attrValue = rowMap.get(column);//输入的值
        String attrName = attrConfig.getAttrName();
        String maxLen = attrConfig.getAttrLength(); // 长度
        String type = attrConfig.getAttrType();
        int isnull = attrConfig.getIsNull();
        if (!StringUtils.isEmpty(attrValue)) {
            if ("NUMBERM".equals(type)) {
                int zs = attrConfig.getAttrZs();// 获取整数位长度
                int xs = attrConfig.getAttrXs();// 获取小数位长度
                //如果是小数位的话
                String xLen = (zs + 1 + xs) + "";// (小数的数据长度限制)
                if (attrValue.indexOf(".") != -1) {//包含
                    if (Integer.parseInt(xLen) < attrValue.length()) {
                        sb.append("第 " + (j) + "行【" + attrName + "】长度不能超过" + Integer.parseInt(xLen) + "！\r\n");
                        bool = false;
                    }
                } else {//不包含
                    if (zs < attrValue.length()) {
                        sb.append("第 " + (j) + "行【" + attrName + "】整数长度不能超过" + Integer.parseInt(xLen) + "！\r\n");
                        bool = false;
                    }
                }
                if (isnull == 0) {
                    if (attrValue.length() <= 0) {
                        sb.append("第 " + (j) + "行【" + attrName + "】长度不能为空！\r\n");
                    }
                }
            } else {
                if (attrValue.length() > 0) {
                    if (!StringUtils.isEmpty(maxLen)) {
                        if (Integer.parseInt(maxLen) < attrValue.length()) {
                            sb.append("第 " + (j) + "行【" + attrName + "】长度不能超过" + Integer.parseInt(maxLen) + "！\r\n");
                            bool = false;
                        } else {
                            if ("NUMBER".equals(type)) {//整数
                                Pattern pattern = Pattern.compile("[1-9]+[0-9]*");
                                Matcher isNum = pattern.matcher(attrValue);
                                if (!isNum.matches()) {
                                    sb.append("第 " + (j) + "行【" + attrName + "】只能填写纯数字 \r\n");
                                    bool = false;
                                }
                            } else if ("radioType".equals(type) || "checkBoxType".equals(type) ||
                                    "selectList".equals(type) || "popList".equals(type)) {
                                if ("5".equals(attrConfig.getModuleType())) {
                                    //要判断用户输入的物料编码是否正确
                                    //获取到用户输入的表名
                                    String wTable = attrConfig.getTabNoName();
                                    //获取到那个属性
                                    String wColumns = attrConfig.getDataSourceColumn();
                                    String wColumn = "";
                                    if (wColumns.indexOf(",") != -1) {//包含逗号
                                        wColumn = wColumns.split(",")[0];
                                    } else {
                                        wColumn = wColumns;
                                    }
                                    Map map = new HashMap();
                                    map.put("columns", wColumn);
                                    map.put("tableName", wTable);
                                    map.put("where", "t." + wColumn + "='" + attrValue.trim() + "' and t.state = 4 ");
                                    List<Map<String, Object>> datLst = jspActionDao.queryList(map);

                                    if (datLst.size() > 0) {
                                        Map<String, Object> dataMap = datLst.get(0);
                                        String idValue = (String) dataMap.get(wColumn);
                                        if (!StringUtils.isEmpty(idValue)) {
                                            attrValue = idValue;
                                            rowMap.put(column, idValue.trim());
                                        }
//											    if(idValue!=null){
//											    	attrValue = idValue;
//											    	rowMap.put(column, idValue.trim());
//											    }
                                    } else {
                                        bool = false;
                                        sb.append("第 " + (j) + "行【" + attrName + "】的值不在其属性来源表!\r\n");
                                    }
                                } else {
                                    //有属性来源表的属性要判断属性的值是否存在属性来源表里
                                    String dsTable = attrConfig.getDataSourceTable();
                                    if (!StringUtils.isEmpty(dsTable)) {
                                        Model modelds = cacheUtil.getModel(dsTable);
                                        //String dsColum=attrConfig.getDataSourceColumn();
                                        String dsColum = attrConfig.getDataSourceShowColumn();
                                        Map<String, String> cond = new HashMap<String, String>();
                                        cond.put("caseColumn", "");
                                        cond.put("sourceTable", modelds.getTableName());
                                        cond.put("sourceCol", dsColum.replace(",", "||'_'||"));
                                        //String selectAttrId=attrConfig.getSelectedConfigAttr();
                                        String caseForeignKey = attrConfig.getCascadedForeignKey();
                                        String ModuleType = attrConfig.getModuleType();
                                        if ("1".equals(ModuleType)) {//关联设置类型
//												String ckey=dsTable+"@@"+dsColum+"@@"+attrValue;
                                            String Id = null;
                                            if (!"checkBoxType".equals(type)) {
                                                Id = getdsTableIdbyColum(cond, ModuleType).get(attrValue);
                                            } else {
                                                //复选框 可能有多个,隔开数据
                                                if (attrValue.indexOf(",") != -1) {//包含逗号
                                                    String ids = "";
                                                    boolean hasNull = false;
                                                    for (String str : attrValue.split(",")) {//一个个的去解析这个值
                                                        String strId = getdsTableIdbyColum(cond, ModuleType).get(str);
                                                        if (!StringUtils.isEmpty(strId)) {
                                                            ids = ids + strId + ",";
                                                        } else {
                                                            hasNull = true;
                                                        }
                                                    }
                                                    if (!hasNull) {
                                                        Id = ids;
                                                    }
                                                } else {
                                                    Id = getdsTableIdbyColum(cond, ModuleType).get(attrValue);
                                                }
                                            }
//													condMap.put(ckey, Id);
                                            //if(Id == null || "".equals(Id)){
                                            if (!StringUtils.isEmpty(Id)) {
                                                attrValue = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                                rowMap.put(column, Id);
                                            } else {
                                                bool = false;
                                                sb.append("第 " + (j) + "行【" + attrName + "】的值不在其属性来源表!\r\n");
                                            }
                                        } else if ("2".equals(ModuleType) && null != caseForeignKey) {
                                            //级联设置型数据，判断作为级联条件的属性值是否存在属性来源表里
                                            AttrConfig caseAttrConfig = cacheUtil.getAttrConfig(dsTable, caseForeignKey);
                                            String sourceCol = dsColum;//+","+caseAttrConfig.getAttrColumn()
                                            cond.put("sourceCol", sourceCol.replace(",", "||'_'||"));
                                            cond.put("conditionCol", caseAttrConfig.getAttrColumn());
                                            cond.put("columnValue", rowMap.get(caseAttrConfig.getAttrColumn()));
//												String ckey=dsTable+"@@"+dsColum+"@@"+caseForeignKey+"@@"+attrValue;
                                            String Id = null;
                                            if (!"checkBoxType".equals(type)) {
                                                Id = getdsTableIdbyColum(cond, ModuleType).get(attrValue);
                                            } else {
                                                //复选框 可能有多个,隔开数据
                                                if (attrValue.indexOf(",") != -1) {//包含逗号
                                                    String ids = "";
                                                    boolean hasNull = false;
                                                    for (String str : attrValue.split(",")) {//一个个的去解析这个值
                                                        String strId = getdsTableIdbyColum(cond, ModuleType).get(str);
                                                        if (!StringUtils.isEmpty(strId)) {
                                                            ids = ids + strId + ",";
                                                        } else {
                                                            hasNull = true;
                                                        }
                                                    }
                                                    if (!hasNull) {
                                                        Id = ids;
                                                    }
                                                } else {
                                                    Id = getdsTableIdbyColum(cond, ModuleType).get(attrValue);
                                                }
                                            }
//												if(condMap.containsKey(ckey))
//											        Id=condMap.get(ckey);
//												else{
//													Id=getdsTableIdbyColum(cond, ModuleType).get(attrValue);
//													condMap.put(column, Id);
//												}
                                            //if(Id == null || "".equals(Id)){
                                            if (!StringUtils.isEmpty(Id)) {
                                                attrValue = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                                rowMap.put(column, Id);

                                            } else {
                                                bool = false;
                                                sb.append("第 " + (j) + "行级联条件【" + caseAttrConfig.getAttrName() + "】的值不在属性来源表!\r\n");
                                            }
                                        } else if ("3".equals(ModuleType)) {// && null != selectAttrId
                                            String Id = null;
                                            if (!"checkBoxType".equals(type)) {
                                                Id = getdsTableIdbyColum(cond, ModuleType).get(attrValue);
                                            } else {
                                                //复选框 可能有多个,隔开数据
                                                if (attrValue.indexOf(",") != -1) {//包含逗号
                                                    String ids = "";
                                                    boolean hasNull = false;
                                                    for (String str : attrValue.split(",")) {//一个个的去解析这个值
                                                        String strId = getdsTableIdbyColum(cond, ModuleType).get(str);
                                                        if (!StringUtils.isEmpty(strId)) {
                                                            ids = ids + strId + ",";
                                                        } else {
                                                            hasNull = true;
                                                        }
                                                    }
                                                    if (!hasNull) {
                                                        Id = ids;
                                                    }
                                                } else {
                                                    Id = getdsTableIdbyColum(cond, ModuleType).get(attrValue);
                                                }
                                            }
//												  Id=getdsTableIdbyColum(cond, ModuleType).get(attrValue);
//												condMap.put(ckey, Id);
                                            //if(Id == null || "".equals(Id)){
                                            if (!StringUtils.isEmpty(Id)) {
                                                attrValue = Id;//将查询到的值，赋给当前输入值，保存到数据库
                                                rowMap.put(column, Id);
                                            } else {
                                                bool = false;
                                                sb.append("第 " + (j) + "行【" + attrName + "】的值不在其属性来源表!\r\n");
                                            }

                                            //选择设置型数据，把设置要隐藏的属性的值置空
//												 String selectedStr=attrConfig.getSelectedConfigAttr();  //获取关联的列的值字符串
//												 String[] splitStr= selectedStr.split("@@");  // 1000:C_004@@1001:C_006,C_005
//									   			 for(int m=0;m<splitStr.length;m++){
//									   				 String[] splitId=splitStr[m].split(":");  //将id和关联的列拆分1  C_007  4 C_007,C_008
//									   				 if(!splitId[0].equals(attrValue)){
//									   					 //拆分后是4 C_007,C_008
//									   					 if(splitId[1].contains(",")){
//									   						 String[] str=splitId[1].split(",");
//									   						   for (int l = 0; l < str.length; l++) {
//									   							    rowMap.put(str[l], null);
//															    }
//									   					 }else{
//									   						 //拆分后是1  C_007
//									   						 rowMap.put(splitId[1], null);
//									   					 }
//									   				 }
//									   			 }
                                        }
                                    }
                                }

                            } else if ("listTree".equals(type)) {
                                String dsTable = attrConfig.getDataSourceTable();
                                String columnV = attrConfig.getDataSourceShowColumn();
                                if (null != dsTable && !"".equals(dsTable)) {
                                    Map map = new HashMap();
                                    map.put("columns", "t.ID");
                                    map.put("tableName", "T_" + dsTable);
                                    map.put("where", "t." + columnV + "='" + attrValue + "' and t.state = 4 ");
                                    List<Map<String, Object>> datLst = jspActionDao.queryList(map);
                                    if (datLst.size() > 0) {
                                        Map<String, Object> dataMap = datLst.get(0);
                                        String idValue = (String) dataMap.get("id");
                                        //if(idValue!=null){
                                        if (!StringUtils.isEmpty(idValue)) {
                                            attrValue = idValue;
                                            rowMap.put(column, idValue.trim());
                                        } else {
                                            bool = false;
                                            sb.append("第 " + (j) + "行【" + attrName + "】的值不在其属性来源表!\r\n");
                                        }
                                    } else {
                                        bool = false;
                                        sb.append("第 " + (j) + "行【" + attrName + "】的值不在其属性来源表!\r\n");
                                    }
                                }

                            } else if ("VARCHAR2".equals(type)) {
                                //获取规则类型
                                String ruleType = attrConfig.getRuleType();
                                if (!StringUtils.isEmpty(ruleType)) {
                                    //规则校验id
                                    String ruleId = attrConfig.getRuleTypeId();
                                    if (ruleType.equals("0")) {//表示是校验唯一
                                        //拿到当前这个值，去跟数据库里面的这个值去比较，判断是否重复
                                        Map map = new HashMap();
                                        map.put("columns", column);
                                        map.put("tableName", model.getTableName());
                                        String where = "t." + column + "='" + attrValue + "' and t.state =4 ";
                                        map.put("where", where);
                                        List<Map<String, Object>> dataLst = jspActionDao.queryList(map);
                                        if (dataLst.size() > 0) {
                                            sb.append("第 " + (j) + "行【" + attrName + "】的值已存在,唯一性校验失败!\r\n");
                                        }
                                    } else if (ruleType.equals("1")) {//表示校验电子邮件
                                        if (!StringUtils.isEmpty(ruleId)) {
                                            CheckRule checkRule = checkRuleDao.getById(ruleId);
                                            String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                            checkRuleExpress = checkRuleExpress.replace("\\", "");//正则表达式
                                            Pattern p = Pattern.compile(checkRuleExpress);
                                            Matcher m = p.matcher(attrValue);
                                            if (!m.matches()) {
                                                bool = false;
                                                sb.append("第 " + (j) + "行【" + attrName + "】不符合邮箱的填写格式!\r\n");
                                            }
                                        }
                                    } else if (ruleType.equals("2")) {//表示校验手机号码
                                        if (ruleId != null) {
                                            CheckRule checkRule = checkRuleDao.getById(ruleId);
                                            String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                            checkRuleExpress = checkRuleExpress.replace("\\", "");//正则表达式
                                            Pattern p = Pattern.compile(checkRuleExpress);
                                            Matcher m = p.matcher(attrValue);
                                            if (!m.matches()) {
                                                bool = false;
                                                sb.append("第 " + (j) + "行【" + attrName + "】不符合手机号码的填写格式!\r\n");
                                            }
                                        }
                                    } else if (ruleType.equals("3")) {//表示校验座机号码
                                        if (!StringUtils.isEmpty(ruleId)) {
                                            CheckRule checkRule = checkRuleDao.getById(ruleId);
                                            String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                            checkRuleExpress = checkRuleExpress.replace("\\", "");//正则表达式
                                            Pattern p = Pattern.compile(checkRuleExpress);
                                            Matcher m = p.matcher(attrValue);
                                            if (!m.matches()) {
                                                bool = false;
                                                sb.append("第 " + (j) + "行【" + attrName + "】不符合座机号的填写格式!\r\n");
                                            }
                                        }
                                    } else if (ruleType.equals("4")) {//表示校验邮政编码
                                        if (!StringUtils.isEmpty(ruleId)) {
                                            CheckRule checkRule = checkRuleDao.getById(ruleId);
                                            String checkRuleExpress = checkRule.getRule_express();//正则表达式
                                            checkRuleExpress = checkRuleExpress.replace("\\", "");//正则表达式
                                            Pattern p = Pattern.compile(checkRuleExpress);
                                            Matcher m = p.matcher(attrValue);
                                            if (!m.matches()) {
                                                bool = false;
                                                sb.append("第 " + (j) + "行【" + attrName + "】不符合邮编的填写格式!\r\n");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if (attrValue.length() <= 0) {//没有输入数据
                    if (isnull == 0) {
                        sb.append("第 " + (j) + "行【" + attrName + "】是必填项！\r\n");
                        bool = false;
                    }

                }
            }
        } else {
            if (isnull == 0) {
                sb.append("第 " + (j) + "行【" + attrName + "】是必填项！\r\n");
                bool = false;
            }
        }
        resMap.put("bool", bool);
        resMap.put("err", sb.toString());
        resMap.put("attrValue", attrValue);
        return resMap;
    }

    private Map<String, String> getdsTableIdbyColum(Map<String, String> cond, String ModuleType) {

        List<GenSelect> list = null;
        if ("1".equals(ModuleType)) {
            cond.put("caseColumn", "");
            list = genJspDao.getSelectAttrData(cond);
        } else if ("2".equals(ModuleType)) {
            //list = genJspDao.getSelectListAttrData(cond);
            list = genJspDao.getSelectAttrData(cond);
        } else if ("3".equals(ModuleType)) {//选择设置
            cond.put("caseColumn", "");
            list = genJspDao.getSelectAttrData(cond);
        }

        Map<String, String> resMap = new HashMap<String, String>();
        for (int i = 0; i < list.size(); i++) {
            resMap.put(list.get(i).getName(), list.get(i).getValue());
        }
        return resMap;
    }

    //返回执行操作的数据Id集合
    private List<String> insert_sxz(Model model, List<Map<Integer, Map<String, String>>> resultList) {
        StringBuilder sql = new StringBuilder();
        StringBuilder sqlForm = new StringBuilder();
        System.out.println(resultList.get(0));
        StringBuilder head = this.sqlHeadInsert(resultList.get(0).get(2));
        StringBuilder sqlHead = new StringBuilder(head);
        int batchCount = 5000;// 每批commit的个数
//        int batchLastIndex = batchCount;// 每批最后一个的下标
        List<String> idLst = new ArrayList<String>();//获取数据id

        if (resultList.size() < batchCount) {
            for (int i = 0; i < resultList.size(); i++) {
                Map<Integer, Map<String, String>> map = resultList.get(i);
                int j = i + 2;
                Map<String, String> rowMap = map.get(j);
                //获取执行的插入语句
                Map<String, Object> res_Map = insertImportBatch(rowMap, j);
                //sql=insertImportBatch(rowMap,j);
                sql = (StringBuilder) res_Map.get("sqlValues");
//				if(model.getIsMoreView()==1){//如果是多视图
//					String idValue =  (String) res_Map.get("idValue");
//					idLst.add(idValue);
//					String idValue =  (String) res_Map.get("idValue");
//					System.out.println(idValue);
//					idLst.add(idValue);
//				}
                if (i != resultList.size() - 1) {
                    sql.append(" union ");
                }
                sqlForm.append(sql);
            }
            sqlHead.append(sqlForm);
            jdbcDao.executeSql(sqlHead.toString());
            sqlHead = new StringBuilder(head);
            sqlForm = new StringBuilder();
        }
//		}else{
//			for(int index=0;index<resultList.size();){
//				List<Map<Integer,Map<String, String>>> partRes=resultList.subList(index, batchLastIndex);
//				for (int i = 0; i < partRes.size(); i++) {
//					Map<Integer,Map<String, String>> map=resultList.get(i);
//					int j = i + 2 ;
//					Map<String, String> rowMap=map.get(j);
//					//sql=insertImportBatch(rowMap,j);
//					//获取执行的插入语句
//					Map<String, Object> res_Map = insertImportBatch(rowMap,j);
//					//sql=insertImportBatch(rowMap,j);
//					sql = (StringBuilder) res_Map.get("sqlValues");
//					if(model.getIsMoreView()==1){//如果是多视图
//						String idValue =  (String) res_Map.get("idValue");
//						idLst.add(idValue);
//					}
//					if(i!=partRes.size()-1){
//						sql.append(" union ");
//					}
//					sqlForm.append(sql);
//					continue;
//				}
//				sqlHead.append(sqlForm);
//				jdbcDao.executeSql(sqlHead.toString());
//				sqlHead=new StringBuilder(head);
//				sqlForm=new StringBuilder();
//				index = batchLastIndex;// 设置下一批下标
//                batchLastIndex = index + (batchCount);//15 20 20  21
//             if(batchLastIndex>resultList.size()){
//             	batchLastIndex = resultList.size();
//             }
//	        }
//		}
        return idLst;
    }

    //private StringBuilder insertImportBatch(Map<String, String> param,int row) {
    private Map<String, Object> insertImportBatch(Map<String, String> param, int row) {

        String modelId = param.get("modelId").toString();
        Model model = cacheUtil.getModel(modelId);
        //表名
        String tableName = param.get("tableName").toString();
        StringBuilder sqlValues = new StringBuilder();
        List<AttrConfig> las = cacheUtil.getAttrList(modelId);
        //获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        String idValue = "";
        sqlValues.append(" select ");
        for (int i = 0; i < las.size(); i++) {
            String colName = las.get(i).getAttrColumn();
            String colType = las.get(i).getDataType();
            if (colType.endsWith("LOB")) {
                continue;
            } else {
                //String value =param.get(colName.toLowerCase());
                String value = param.get(colName.toUpperCase());
                if (value != null) {
                    if (value.startsWith("{") && value.endsWith("}")) {
                        value = JspUtil.formatSelectCol(value);
                    }
                    value = StringUtil.escapeSql(value);
                    sqlValues.append("'").append(value).append("',");
                } else {
                    sqlValues.append(" null,");
                }
            }
        }

//	    if("1".equals(model.getClassType())){
//	        sqlValues.append("'").append(param.get(String.valueOf(row))).append("', '");
//	    }else{
        //sqlValues.append(tableName).append(TableConst.SEQUENCESUFFIX).append(".nextVal, '");
//	    	if(model.getIsMoreView()==1){//说明是多视图
//	    		Map<String,String> cond=new HashMap<String, String>();
//	            cond.put("tableSeqNextval", tableName+TableConst.SEQUENCESUFFIX+".nextval");
//	               idValue=jspActionDao.selectIdBySeq(cond);
//	            sqlValues.append("'"+idValue).append("', '");
//	    	}else{
        sqlValues.append("get_seq('" + tableName).append(TableConst.SEQUENCESUFFIX).append("'), '");
//	    	}
//	     }
        sqlValues.append(user.getUserId().longValue()).append("', '");
        sqlValues.append(user.getUserName()).append("', sysdate,  0, ");
        sqlValues.append(Flag.STATE_0.getCode()).append(", ");
        sqlValues.append(Flag.STATUS_0.getCode()).append(", ");        // 数据状态
        sqlValues.append(Flag.DISPATCH_0.getCode()).append(", ");
        sqlValues.append(StringUtil.safeNull(param.get("pid"))).append(", ");
        sqlValues.append(StringUtil.safeNull(param.get("mainid")));
        sqlValues.append(" from dual");

        Map<String, Object> res_Map = new HashMap<>();
        res_Map.put("idValue", idValue);
        res_Map.put("sqlValues", sqlValues);
        //	return sqlValues;
        return res_Map;
    }

    private StringBuilder sqlHeadInsert(Map<String, String> param) {
        String modelId = param.get("modelId").toString();
        //表名
        String tableName = param.get("tableName").toString();
        StringBuilder sqlHeader = new StringBuilder();
        List<AttrConfig> las = cacheUtil.getAttrList(modelId);

        sqlHeader.append("insert into ").append(tableName).append("(");
        for (int i = 0; i < las.size(); i++) {
            String colName = las.get(i).getAttrColumn();
            String colType = las.get(i).getDataType();
            if (colType.endsWith("LOB")) {
                continue;
            } else {
                sqlHeader.append(colName).append(",");
            }
        }
        sqlHeader.append("id, creater_id, creater_name, creater_time, version, state, status, dis_flag, pid, mainid)");
        return sqlHeader;
    }

    /**
     * <p>TODO 刘晶添加多视图导入这块用到的方法</p>
     * <p>@param param
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年12月1日下午5:10:33
     */
    private StringBuilder InsertSqlHeader(Model model, List<AttrConfig> jspAttrLst) {

        StringBuilder sqlHeader = new StringBuilder();
        sqlHeader.append("insert into ").append(TableConst.TABLEPREFIX + model.getId()).append("(");
        for (AttrConfig conf : jspAttrLst) {
            String colName = conf.getAttrColumn();
            String colType = conf.getDataType();
            if (colType.endsWith("LOB")) {
                continue;
            } else {
                sqlHeader.append(colName).append(",");
            }
        }
        sqlHeader.append("id, creater_id, creater_name, creater_time, version, state, status, dis_flag, pid, mainid)");
        return sqlHeader;
    }

    /**
     * <p>TODO 多视图模块导入到数据库方法</p>
     * <p>@param param
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年12月1日下午5:21:48
     */
    private Map<String, Object> ImpBatchLst(Model model, List<AttrConfig> jspAttrLst, Map<String, Object> dataRowMap) {
        StringBuilder sqlValues = new StringBuilder();
        //获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        String idValue = "";
        sqlValues.append(" select ");
        for (AttrConfig conf : jspAttrLst) {
            String colName = conf.getAttrColumn();
            String colType = conf.getDataType();
            if (colType.endsWith("LOB")) {
                continue;
            } else {
                String value = (String) dataRowMap.get(colName.toLowerCase());//转换成小写的方法
                if (!StringUtils.isEmpty(value)) {
                    if (value.startsWith("{") && value.endsWith("}")) {
                        value = JspUtil.formatSelectCol(value);
                    }
                    value = StringUtil.escapeSql(value);
                    sqlValues.append("'").append(value).append("',");
                } else {
                    sqlValues.append(" null,");
                }
            }
        }
        Map<String, String> cond = new HashMap<String, String>();
        cond.put("tableSeqNextval", model.getTableName() + TableConst.SEQUENCESUFFIX + ".nextval");
        idValue = jspActionDao.selectIdBySeq(cond);
        sqlValues.append("'" + idValue).append("', '");
        sqlValues.append(user.getUserId().longValue()).append("', '");
        sqlValues.append(user.getUserName()).append("', sysdate,  0, ");
        sqlValues.append(Flag.STATE_0.getCode()).append(", ");
        sqlValues.append(Flag.STATUS_0.getCode()).append(", ");        // 数据状态
        sqlValues.append(Flag.DISPATCH_0.getCode()).append(", ");
        sqlValues.append(StringUtil.safeNull(dataRowMap.get("pid"))).append(", ");
        sqlValues.append(StringUtil.safeNull(dataRowMap.get("mainid")));
        sqlValues.append(" from dual");
        Map<String, Object> ruRowMap = new HashMap<>();
        dataRowMap.put("ID", idValue);//获取这条多视图数据的ID
        ruRowMap.put("sqlValues", sqlValues);//新增执行的sql语句
        ruRowMap.put("dataRow", dataRowMap);//新增执行的sql语句
        return ruRowMap;
    }

    @Override
    public String autoCode(String seqName, int length) {
        try {
            return jdbcDao.genSeqGetVal(seqName, length);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "获取序列" + seqName + "长度为" + length + "的值失败！";
    }

    /**
     * <p>TODO table 模型表里的数据</p>
     *
     * @param : @param tabName
     * @author : xiaoliu
     * @date :2017年3月21日下午2:22:35
     */
    @Override
    public int queryModelCount(Map<String, Object> param) {
//		String modelId  = (String) param.get("modelId");
//		List<Model> subModel=modelDao.isHasSub(modelId);
//		for(Model sub : subModel){
//			Map<String, Object> map = new HashMap<>();
//			map.put("tableName", sub.getTableName());
//			queryModelCount(map);
//		}
        return jspActionDao.queryModelCount(param);
    }

    private StringBuilder analysisGjQuery(Map<String, Object> param, AttrConfig ac, String key) {
        StringBuilder where = new StringBuilder();
        String[] query = param.get(key).toString().split(";");
        for (int i = 0; i < query.length; i++) {
            String luoJi = 0 == i ? " and (" : " or ";
            where.append(luoJi);

            //类型为VARCHAR2 查询方式：1.左匹配 2.右匹配 3.全匹配 4.模糊匹配
            if ("VARCHAR2".equals(ac.getAttrType())) {
                if ("1".equals(ac.getQueryType())) {
                    where.append(key).append(" like '" + query[i] + "%' ");

                } else if ("2".equals(ac.getQueryType())) {
                    where.append(key).append(" like '%" + query[i] + "' ");

                } else if ("3".equals(ac.getQueryType())) {
                    where.append(key).append(" = '").append(query[i]).append("' ");

                } else if ("4".equals(ac.getQueryType())) {
                    where.append(key).append(" like '%" + query[i] + "%' ");
                }
            }

            //类型为NUMBERM、NUMBER 查询方式：1.大于 2.小于 3.等于 4.大于等于 5.小于等于
            if ("NUMBERM".equals(ac.getAttrType()) || "NUMBER".equals(ac.getAttrType())) {
                if ("1".equals(ac.getQueryType())) {
                    where.append(key).append(" > " + query[i] + " ");

                } else if ("2".equals(ac.getQueryType())) {
                    where.append(key).append(" < " + query[i] + " ");

                } else if ("3".equals(ac.getQueryType())) {
                    where.append(key).append(" = " + query[i] + " ");

                } else if ("4".equals(ac.getQueryType())) {
                    where.append(key).append(" >= " + query[i] + " ");

                } else if ("5".equals(ac.getQueryType())) {
                    where.append(key).append(" <= " + query[i] + " ");
                }
            }

            //类型为NUMBERM、NUMBER 单值查询 范围值查询
            if ("DATE".equals(ac.getAttrType())) {
                if (query[i].indexOf("&") != -1) {
                    String[] dateArry = query[i].split("&");
                    where.append(" to_date(" + key + ",'yyyy-mm-dd') ").append(" between to_date('" + dateArry[0] + "','yyyy-mm-dd') and to_date('" + dateArry[1] + "','yyyy-mm-dd') ");
                } else {
                    where.append(" to_date(" + key + ",'yyyy-mm-dd') ").append(" = to_date('" + query[i] + "','yyyy-mm-dd') ");
                }
            }

            //selectList、radioType、checkBoxType、popList、listTree
            if ("selectList".equals(ac.getAttrType()) || "radioType".equals(ac.getAttrType())
                    || "checkBoxType".equals(ac.getAttrType()) || "popList".equals(ac.getAttrType())
                    || "listTree".equals(ac.getAttrType())) {
                where.append(key).append(" = '").append(query[i]).append("' ");
            }

            //CLOB、mailType、hideType
            if ("CLOB".equals(ac.getAttrType()) || "mailType".equals(ac.getAttrType())
                    || "hideType".equals(ac.getAttrType())) {
                where.append(key).append(" like '%" + query[i] + "%' ");
            }
        }
        if (where.indexOf("c_") != -1) {
            return where.append(" )");
        } else {
            StringBuilder empty = new StringBuilder();
            return empty;
        }
    }

    private Map<String, AttrConfig> getNewAttrConfig(String modelId) {
        LinkedHashMap<String, AttrConfig> ma = new LinkedHashMap<String, AttrConfig>();
        Map<String, String> cond = new HashMap<>();
        cond.put("modelId", modelId);
        List<AttrConfig> attrList = attrConfigDao.queryValidAttributeList(cond);
        for (AttrConfig ac : attrList) {
            ma.put(ac.getAttrColumn(), ac);
        }
        return ma;
    }

    /**
     * <p>TODO</p>
     *
     * @param : @param param
     * @param : @return
     * @author : xiaoliu
     * @date :2017年3月27日下午3:54:30
     */

    @Override
    public int checkcolumnName(Map<String, Object> param) {

        return jspActionDao.checkcolumnName(param);
    }


    @Override
    public List<DataViewFlow> queryDataViewFlows(Map map) {
        return viewDao.queryDataViewFlows(map);

    }


    @Override
    public int updataDataViewFlow(DataViewFlow g) {
        return viewDao.updataDataViewFlow(g);

    }


    @Override
    public int insertDataFlow(DataViewFlow g) {
        return viewDao.insert(g);

    }

    /**
     * <p>TODO</p>
     *
     * @param : @param modelId
     * @param : @return
     * @author : xiaoliu
     * @date :2017年4月7日下午2:10:46
     */

    @Override
    public int deleteDataFlow(Map map) {
        return viewDao.deleteDataFlow(map);

    }

    /**
     * <p>TODO 根据modelId,sysCode 生成一个拼接的XML文件</p>
     *
     * @param : @param map（modelId 模型Id  sysCode  目标系统code）
     * @param : @return String 拼接的字符串
     * @author : xiaoliu
     * @date :2017年6月14日上午9:33:47
     */
    @Override
    public Map<String, Object> creatXml(Map map) {
        StringBuilder sb = new StringBuilder();
        List<String> idLst = new ArrayList<String>();
        Map<String, Object> param = new HashMap<>();
        String modelId = (String) map.get("modelId");
        String tableName = TableConst.TABLEPREFIX + modelId + TableConst.DISPATCHSUFFIX;
        map.put("tableName", tableName);
        //系统列
        StringBuilder sysCols = SystemAttributeFactory.getSystemColumnsBuilder();
        //模型的属性列
        String busiCols = cacheUtil.getQueryColumns(modelId);
        //分发表独有的属性列
        //String disCols ="dis_flag,error_text,origin_id,target_id,target_code,target_name";
        String disCols = "origin_id,target_id,target_code,target_name";
        String cols = sysCols.append(busiCols).append(disCols).toString();
        map.put("columns", cols.subSequence(0, cols.length()));
        List<Map<String, Object>> dataList = jspActionDao.getDistributedData(map);
        if (dataList.size() < 1) {
            return null;
        } else {
            sb.append("<datas>");
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> columnMap = dataList.get(i);
                Set<String> keySet = columnMap.keySet();
                sb.append("<data>");
                for (String string : keySet) {
                    sb.append("<").append(string).append(">");
                    sb.append(columnMap.get(string));
                    if ("ID".equalsIgnoreCase(string)) {
                        idLst.add(columnMap.get(string).toString());
                    }
                    sb.append("</").append(string).append(">");
                }
                sb.append("</data>");
            }
            sb.append("</datas>");
        }
        param.put("XMLData", sb.toString());
        param.put("idLst", idLst);
        return param;
    }

    /**
     * <p>TODO  根据modelId,flag,errorText,idLst变更批量分发的数据</p>
     * <p>@param map （modelId,flag,errorText,idLst）
     * <p>@return int </p>
     *
     * @author : xiaoliu
     * @date :2017年6月14日上午9:43:49
     */
    @Override
    public int batchDisTableFlag(Map map) {
        String modelId = (String) map.get("modelId");
        String tableName = TableConst.TABLEPREFIX + modelId + TableConst.DISPATCHSUFFIX;
        map.put("tableName", tableName);
        int count = jspActionDao.batchDisTableFlag(map);
        return count;

    }

    @Override
    public int batchDisTableFlag2(Map map) {
        String modelId = (String) map.get("modelId");
        String tableName = TableConst.TABLEPREFIX + modelId + TableConst.DISPATCHSUFFIX;
        String flag = (String) map.get("flag");
        List<String> failIdList = (List<String>) map.get("failIdList");

        for (String str : failIdList) {
            String id = str.split("@@")[0];
            String errorText = str.split("@@")[1];
            Map map2 = new HashMap();
            map2.put("id", id);
            map2.put("errorText", errorText);
            map2.put("tableName", tableName);
            map2.put("flag", flag);

            jspActionDao.batchDisTableFlag2(map2);
        }
        return 0;

    }

//    public String columnValide(){
//
//		return null;
//
//    }


    /**
     * <p>TODO 多视图中，同一批导入数据，唯一性校验，是不是有重复的数据</p>
     * <p>@param dataMap
     * <p>@param jspAttrs
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年12月1日上午11:11:01
     */
    public Map<String, Object> checkSXSSWorkImport(Map<Integer, Map<String, String>> dataMap, List<AttrConfig> jspAttrs) {
        boolean flag = true;
        StringBuilder sb = new StringBuilder();
        Map<String, Object> checkMap = new HashMap<>();
        List<AttrConfig> jspAttrLst = new ArrayList<>();
        for (AttrConfig attrConfig : jspAttrs) {
            if ("VARCHAR2".equals(attrConfig.getAttrType())) {//是字符格式
                //获取规则类型
                String ruleType = attrConfig.getRuleType();
                if (ruleType != null) {
                    if (ruleType.equals("0")) {//表示是校验唯一
                        jspAttrLst.add(attrConfig);
                    }
                }
            }
        }
        if (dataMap.size() > 5000) {
            flag = false;
            sb.append("同批次数据导入，请将数据控制在5000条以内！r\n");
        } else {
            if (jspAttrLst.size() > 0) {
                for (int i = 0; i < jspAttrLst.size(); i++) {
                    AttrConfig config = jspAttrLst.get(i);
                    String column = config.getAttrColumn().toLowerCase();//列名
                    String attrName = config.getAttrName();
                    for (int m = 1; m < dataMap.size(); m++) {
                        Map<String, String> rowMapQ = dataMap.get(m);
                        String attrValueQ = rowMapQ.get(column);//输入的值
                        if (!StringUtils.isEmpty(attrValueQ)) {
                            for (int n = m + 1; n < dataMap.size(); n++) {
                                Map<String, String> rowMapH = dataMap.get(n);
                                String attrValueH = rowMapH.get(column);//输入的值
                                if (!StringUtils.isEmpty(attrValueH)) {
                                    if (attrValueQ.trim().equals(attrValueH.trim())) {
                                        flag = false;
                                        sb.append("同批次数据导入，第" + m + "和第" + n + "行，" + attrName + "的值一样，唯一性校验失败！\r\n");
                                    }
                                }
                            }
                        }

                    }
                }
            }
        }
        checkMap.put("flag", flag);
        checkMap.put("errorResult", sb.toString());
        return checkMap;
    }

    //同批次数据唯一性校验（验证）
    public Map<String, Object> checkImport(List<Map<Integer, Map<String, String>>> attrValueLst, List<AttrConfig> jspAttrs) {
        boolean flag = true;
        StringBuilder sb = new StringBuilder();
        Map<String, Object> checkMap = new HashMap<>();
        List<AttrConfig> jspAttrLst = new ArrayList<>();
        for (AttrConfig attrConfig : jspAttrs) {
            if ("VARCHAR2".equals(attrConfig.getAttrType())) {//是字符格式
                //获取规则类型
                String ruleType = attrConfig.getRuleType();
                if (ruleType != null) {
                    if (ruleType.equals("0")) {//表示是校验唯一
                        jspAttrLst.add(attrConfig);
                    }
                }
            }
        }
        if (attrValueLst.size() > 5000) {
            flag = false;
            sb.append("同批次数据导入，请将数据控制在5000条以内！r\n");
        } else {
            if (jspAttrLst.size() > 0) {
                for (int i = 0; i < jspAttrLst.size(); i++) {
                    AttrConfig config = jspAttrLst.get(i);
                    String column = config.getAttrColumn().toLowerCase();//列名
                    String attrName = config.getAttrName();
                    for (int j = 0; j < attrValueLst.size(); j++) {
                        Map<Integer, Map<String, String>> map = attrValueLst.get(j);//获取到sheet页的所有行数据
                        for (int m = 1; m < map.size(); m++) {
                            Map<String, String> rowMapQ = map.get(m);
                            String attrValueQ = rowMapQ.get(column);//输入的值
                            if (!StringUtils.isEmpty(attrValueQ)) {
                                for (int n = m + 1; n < map.size(); n++) {
                                    Map<String, String> rowMapH = map.get(n);
                                    String attrValueH = rowMapH.get(column);//输入的值
                                    if (!StringUtils.isEmpty(attrValueH)) {
                                        if (attrValueQ.trim().equals(attrValueH.trim())) {
                                            flag = false;
                                            sb.append("同批次数据导入，第" + m + "和第" + n + "行，" + attrName + "的值一样，唯一性校验失败！\r\n");
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }
        checkMap.put("flag", flag);
        checkMap.put("errorResult", sb.toString());
        return checkMap;
    }

    /**
     * <p>TODO</p>
     *
     * @param : @param param
     * @param : @return
     * @author : xiaoliu
     * @date :2017年8月2日下午1:51:52
     */

    @Override
    public PageInfo queryNoTabList(Map<String, Object> param) {
        PageInfo<List<Map>> pageInfo = null;
        String tableName = param.get("tableName").toString();
        String modelId = param.get("modelId").toString();
        String operColumn = param.get("operColumn").toString();
        param.put("tableName", tableName);//数据来源表的表名
        param.put("modelId", modelId);//本模型Id

        // 业务属性
        StringBuilder where = new StringBuilder();
        Map<String, AttrConfig> ma = cacheUtil.getAttrMap(modelId);
        //获取实时的AttrConfig 不从缓存拿数据
        Map<String, AttrConfig> map = this.getNewAttrConfig(modelId);
        boolean contains = param.containsKey("search");
        if (contains) {
            if (operColumn != null) {
                AttrConfig ac = ma.get(operColumn);
                if (ac != null) {
                    AttrConfig config = map.get(operColumn);//获取它的属性设置关系
                    String dataSourceColumn = config.getDataSourceColumn();//操作的属性列
                    if (dataSourceColumn.indexOf(",") != -1) {//说明含有逗号分隔，有多个属性
                        for (int i = 0; i < dataSourceColumn.split(",").length; i++) {
                            String dcolumn = dataSourceColumn.split(",")[i];
                            boolean tcon = param.containsKey(dcolumn.toLowerCase());
                            if (tcon) {
                                if (param.get(dcolumn.toLowerCase()).toString() != null) {
                                    if (i == 0) {
                                        where.append(" and ").append(dcolumn).append(" like '%").append(param.get(dcolumn.toLowerCase()).toString()).append("%'");
                                    } else {
                                        where.append(" and ").append(dcolumn).append(" like '%").append(param.get(dcolumn.toLowerCase()).toString()).append("%' ");
                                    }
                                }
                            }
                        }
                    } else {
                        boolean tcon = param.containsKey(dataSourceColumn.toLowerCase());
                        if (tcon) {
                            if (param.get(dataSourceColumn.toLowerCase()).toString() != null) {
                                where.append(" and ").append(dataSourceColumn).append(" like '%").append(param.get(dataSourceColumn.toLowerCase()).toString()).append("%' ");
                            }
                        }
                    }
                }
            }
        }
        //自定义条件，如万达要求查询物料不包含92类，在页面中条件设置为pageRequest.perconditions = 'and substr(t.lbbm,0,2)!=92'; 暂时性，如有好办法再替换
        if (param.containsKey("perconditions")) {
            where.append(param.get("perconditions"));
        }
        param.put("where", where);

        Object pNo = param.get("pageNum");
        int pageNum, pageSize;
        // export
        if (pNo != null && !"NaN".equals(pNo)) {
            pageNum = Integer.parseInt(pNo.toString());//页码
        } else {
            pageNum = 1;
        }
        //pageSize=0时不分页
        pageSize = Integer.parseInt(param.get("limit").toString());//每页条数
        PageHelper.startPage(pageNum, pageSize);//分页  注释掉后就不会进行分页
        List<Map<String, Object>> list = null;
        list = jspActionDao.queryNoTabList(param);

        pageInfo = new PageInfo(list);

        return pageInfo;

    }

    /**
     * <p>TODO 针对万达定制型唯一校验的方法</p>
     * <p>@param param
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年9月20日上午9:28:40
     */
    @Override
    public int checkcolumnNameToWanDa(Map<String, Object> param) {

        return jspActionDao.checkcolumnNameToWanDa(param);
    }

    /**
     * 查询当前数据库登录用户下的表或视图的全部字段属性
     *
     * @param tableName
     * @return
     */
    public List<Map<String, Object>> queryAlltabcolumns(String tableName) {
        List<Map<String, Object>> columnsList = new ArrayList<Map<String, Object>>();
        try {
            // 获取当前数据库用户名dbUsername，如果返回值为空则默认返回值为"DM"
            // 本想获取jdbc.properties文件中的jdbc.username参数，但是担心windows和linux系统下获取路径不一致，所以从系统参数中获取
            String dbUsername = sysParameterService.getSysParamValue("dbUsername", "DM");
            HashMap dmap = new HashMap();
            // 传值当前数据库登录名，如果数据库一个实例下多个用户有相同表，则会查询结果重复，所以传递此参数
            dmap.put("dbUsername", dbUsername.toUpperCase());
            dmap.put("tableName", tableName.toUpperCase());
            // 根据前台传递tableName值，查询此表或视图的全部字段属性
            columnsList = jspActionDao.queryAlltabcolumns(dmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return columnsList;
    }

    /**
     * 将视图中关联的字段加入查询字段中
     *
     * @param columnsList
     * @param cols
     * @return
     */
    public String addColumns(List<Map<String, Object>> columnsList, String cols) {
        try {
            if (columnsList != null && columnsList.size() > 0) {
                String column_name = "";
                for (int x = 0; x < columnsList.size(); x++) {
                    column_name = (String) columnsList.get(x).get("columnName");
                    if (cols.indexOf(column_name) < 0) {
                        cols += column_name + ",";
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cols;
    }

    /**
     * 将视图中关联的字段加入ma
     *
     * @param ma
     * @param sysCols
     * @param columnsList
     * @return
     */
//	public Map<String, AttrConfig> addma(Map<String, AttrConfig> ma, String sysCols, List<Map<String, Object>> columnsList) {
//		try {
//			if (columnsList != null && columnsList.size() > 0) {
//				String column_name = "";
//				for (int x = 0; x < columnsList.size(); x++) {
//					column_name = (String) columnsList.get(x).get("columnName");
//					if (sysCols.indexOf(column_name) < 0) {
//						if (ma.get(column_name.toUpperCase()) == null) {
//							AttrConfig ac = new AttrConfig();
//							ac.setAttrColumn(column_name);
//							ma.put(column_name, ac);
//						}
//					}
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return ma;
//	}

    /**
     * 将视图中关联的字段加入ma
     *
     * @param map
     * @param sysCols
     * @param columnsList
     * @return
     */
    public Map<String, AttrConfig> addmap(Map<String, AttrConfig> map, String sysCols, List<Map<String, Object>> columnsList) {
        try {
            if (columnsList != null && columnsList.size() > 0) {
                String column_name = "";
                for (int x = 0; x < columnsList.size(); x++) {
                    column_name = (String) columnsList.get(x).get("columnName");
                    if (sysCols.indexOf(column_name) < 0) {
                        if (map.get(column_name.toUpperCase()) == null) {
                            AttrConfig ac = new AttrConfig();
                            ac.setAttrColumn(column_name);
                            ac.setIsOrder(0);
                            map.put(column_name, ac);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 变更、冻结、解冻-- (中纺srm接口用)
     *
     * @param param
     * @return
     * @author jiangyh
     * @date 2017-09-25
     */
    @SuppressWarnings("serial")
    @Override
    public boolean insertBg_zf(Map<String, Object> param) {
        List<String> sqls = new ArrayList<String>();
        final String tableName = param.get("tableName").toString();
        //查询从表
        List<Model> subModels = modelDao.isHasSub(tableName.split("_")[1]);
        if (!subModels.isEmpty()) {
            Map<String, String> m = new HashMap<String, String>() {
                {
                    put("tableSeqNextval", tableName + TableConst.SEQUENCESUFFIX + ".nextVal");
                }
            };
            String[] ids = param.get("ids").toString().split(",");
            for (String id : ids) {
                String bgId = jspActionDao.selectIdBySeq(m);
                param.put("bgId", bgId);
                param.put("ids", id);
                sqls = sqlUtil.genBgInsertSql(param, sqls);
                ///刘晶-往从表分发数据,目前
                for (Model sub : subModels) {
                    Map<String, Object> subParam = genSubProcessParam(sub.getTableName(), id);
                    if (subParam != null) {
                        //递归调用
                        subParam.put("operType", param.get("operType"));
                        subParam.put("modelId", sub.getId());
                        subParam.put("tableName", sub.getTableName() + TableConst.MODIFYSUFFIX);
                        subParam.put("mainDataId", bgId); //从表保存变更数据主键
                        sqls = sqlUtil.genBgInsertSql(subParam, sqls);
                    }
                }
            }
        } else {
            //生成插入sql
            sqls = sqlUtil.genBgInsertSql(param, sqls);
        }
        boolean ret = jdbcDao.executeSqlList(sqls, true);
        return ret;
    }

    @Override
    public boolean update_zf(Map<String, Object> param, SysUser user) {
        String sql = sqlUtil.genUpdateSql_zf(param, user);
        return jdbcDao.executeSql(sql);
    }

    @Override
    public Map<String, Object> excelSXSSWorkImport(String modelId, InputStream input) {

        /**======第一步   获取模型及操作属性，及属性的设置信息和与当前登录人有关的操作权限等=======================================================*/
        //获取session里面当前登录人的信息
        //    SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        //获取该动态模型的建模信息
        Model model = cacheUtil.getModel(modelId);
        //获取返回的结果集
        Map<String, Object> result_map = new HashMap<>();

        // 声明一个在新增页面操作的模型设置集合属性列
        List<AttrConfig> jspAttrLst = new ArrayList<AttrConfig>();

        boolean opflag = false; // 默认此次导入操作不成功
        //定义一个查询非多视图获取当前登录人可视属性的map集合--mapCon

        //定义一个查询多视图获取所有可视属性的map集合 --parm
        Map<String, String> parm = new HashMap<String, String>();
        parm.put("modelId", modelId);//模型ID

        //定义一个属性设置集合
        List<AttrConfig> configLst = attrConfigDao.queryValidAttributeList(parm); //这个不包含当前登录人的属性权限，包含的是所有的可视属性
        //获取新增页面操作的属性列集合
        for (AttrConfig attrConfig : configLst) { //在新增页面展示，且不是编码格式
            if (attrConfig.getShowPage().contains("2") && !"4".equals(attrConfig.getModuleType())) { // 在新增页面展示
                jspAttrLst.add(attrConfig);
            }
        }

        Map<String, Object> checkModelRsuMap = ExcelUtil.excelSXSSWorkImport(modelId, input, jspAttrLst); //返回的值和属性对应值的map集合
        String errTxt = (String) checkModelRsuMap.get("errTxt");    //第一 步，获取校验模型模板的错误信息
        if (!StringUtils.isEmpty(errTxt)) {//如果错误原因不为空
            try {
                opflag = false;
                String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                ExportUtil.errTxt(errTxt, fileName);
                result_map.put("err_fileName", fileName);
                result_map.put("bool", opflag);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {//错误原因为空,则导出校验的模板不存在问题
            Map<Integer, Map<String, String>> dataMap = (Map<Integer, Map<String, String>>) checkModelRsuMap.get("dataLst");//Excel里面的有效数据
            if (!MapUtils.isEmpty(dataMap)) {
                Map<String, Object> checkImpResult = this.checkSXSSWorkImport(dataMap, jspAttrLst);//多视图同批次数据唯一性校验
                boolean flag = (boolean) checkImpResult.get("flag");
                if (flag) {//如果flag为true
                    result_map = this.checkDataLst(dataMap, model, jspAttrLst);//整行整行的校验数据//校验属性值
                    if ((Boolean) result_map.get("bool")) {//判断校验的返回结果是否为true
                        List<Map<String, Object>> dataLst = (List<Map<String, Object>>) result_map.get("dataLst");//有效的操作数据
                        //插入数据库
                        if (dataLst.size() > 0) {//有效数据不为空
                            List<Map<String, Object>> dataViewLst = this.InsertSXSSData(model, dataLst, jspAttrLst);
                            if (!CollectionUtils.isEmpty(dataViewLst)) {//如果多视图校验的数据不为空
                                List<String> sqls = this.InsertDataViewFlow(model, dataViewLst);//那么执行往dataView表里新增数据
                                if (!CollectionUtils.isEmpty(sqls)) {
                                    for (String sql : sqls) {
                                        jdbcDao.executeSql(sql);
                                    }
                                    //jdbcDao.executeSqlList(sqls, false);
                                }
                            }
                            opflag = true;
                        } else {
                            try {
                                String errText = "没有效的操作数据，请检查完，在操作！";
                                String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                                ExportUtil.errTxt(errText, fileName);
                                result_map.put("err_fileName", fileName);
                                result_map.put("bool", false);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {//error
                        String resTxt = (String) result_map.get("error");
                        String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                        try {
                            ExportUtil.errTxt(resTxt, fileName);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        result_map.put("err_fileName", fileName);
                        result_map.put("bool", false);
                    }
                } else {
                    String dataErr = (String) checkImpResult.get("errorResult");
                    String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                    try {
                        ExportUtil.errTxt(dataErr, fileName);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    result_map.put("err_fileName", fileName);
                    result_map.put("bool", flag);
                }
            } else {
                opflag = false;
                String dataErr = "没有有效的数据";
                String fileName = model.getModelName() + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                try {
                    ExportUtil.errTxt(dataErr, fileName);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                result_map.put("err_fileName", fileName);
                result_map.put("bool", opflag);
            }
        }
        return result_map;
    }


    /**
     * <p>TODO 多视图数据导入调用的方法</p>
     * <p>@param model
     * <p>@param dataLst
     * <p>@param jspAttrLst
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年12月1日下午5:07:49
     */
    private List<Map<String, Object>> InsertSXSSData(Model model, List<Map<String, Object>> dataLst, List<AttrConfig> jspAttrLst) {
        StringBuilder sql = new StringBuilder();
        StringBuilder sqlForm = new StringBuilder();
        StringBuilder head = this.InsertSqlHeader(model, jspAttrLst);
        StringBuilder sqlHead = new StringBuilder(head);
        int batchCount = 5000;// 每批commit的个数
        List<Map<String, Object>> dataViewLst = new ArrayList<Map<String, Object>>();

        if (dataLst.size() < batchCount) {
            for (int i = 0; i < dataLst.size(); i++) {
                Map<String, Object> rowData = dataLst.get(i);
                Map<String, Object> returnRowMap = this.ImpBatchLst(model, jspAttrLst, rowData);
                sql = (StringBuilder) returnRowMap.get("sqlValues");//返回执行的SQL语句
                Map<String, Object> rowDataMap = (Map<String, Object>) returnRowMap.get("dataRow");//封装好的带数据ID的数据状态
                dataViewLst.add(rowDataMap);
                if (i != dataLst.size() - 1) {
                    sql.append(" union ");
                }
                sqlForm.append(sql);
            }
            sqlHead.append(sqlForm);
            jdbcDao.executeSql(sqlHead.toString());
            sqlHead = new StringBuilder(head);
            sqlForm = new StringBuilder();
        }
        return dataViewLst;
    }

    /**
     * <p>TODO 往dataViewFlow表里添加数据</p>
     * <p>@param model
     * <p>@param dataLst
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年12月2日上午9:55:30
     */
    private List<String> InsertDataViewFlow(Model model, List<Map<String, Object>> dataLst) {

        List<String> sqls = new ArrayList<String>();
        String modelId = model.getId();//获取模型的ID

        if (!CollectionUtils.isEmpty(dataLst)) {
            for (int i = 0; i < dataLst.size(); i++) {
                String idValue = "";
                Map<String, Object> rowData = dataLst.get(i);//获取具体的操作行数
                if (!MapUtils.isEmpty(rowData)) {
                    boolean rowflag = true;


                    List<AttrGroup> groupLst = attrGroupDao.queryGroupByModelId(modelId);
                    if (!CollectionUtils.isEmpty(groupLst)) {//属性组集合
                        for (AttrGroup grop : groupLst) {
                            StringBuilder sqlValues = new StringBuilder();
                            String groupId = grop.getId();
                            List<AttrConfig> alst = cacheUtil.getAttrListByGroup(modelId, groupId);
                            if (!CollectionUtils.isEmpty(alst)) {
                                for (AttrConfig conf : alst) {
                                    String col = conf.getAttrColumn().toLowerCase();
                                    String colVal = (String) rowData.get(col);
                                    if (!StringUtils.isEmpty(colVal)) {//判断它为空，如果都为空，就说明没有选中
                                        rowflag = false;
                                    }
                                }
                            }
                            sqlValues.append("insert into DATA_VIEW_FLOW (ID,DATA_ID,MODEL_ID,GROUP_ID,OPER_TYPE,IS_SELECTED)");
                            sqlValues.append(" select ");
                            Map<String, String> cond = new HashMap<String, String>();
                            cond.put("tableSeqNextval", "DATA_VIEW_FLOW" + TableConst.SEQUENCESUFFIX + ".nextval");
                            idValue = jspActionDao.selectIdBySeq(cond);
                            sqlValues.append("'" + idValue).append("',");
                            sqlValues.append("'" + rowData.get("ID")).append("', '");
                            sqlValues.append(modelId).append("', '");
                            sqlValues.append(groupId).append("', '");        // 数据状态
                            sqlValues.append("submit").append("', '");
                            if (rowflag) {//如果rowFlag 为true，则表示属性全部为空，没有选中
                                sqlValues.append("0'");
                            } else {//表示有一个（任意一个属性）有值，则为选中状态
                                sqlValues.append("1'");
                            }
                            sqlValues.append(" from dual");
                            sqls.add(sqlValues.toString());
                        }
                    }
                }
            }
        }
        return sqls;
    }

    /**
     * <p>TODO 导出当前操作模型下的数据</p>
     *
     * @param : @param modelId
     * @param : @param resp
     * @author : xiaoliu
     * @date :2017年12月4日上午8:10:11
     * 今天 看了一个文章，受启发了，为什么我没想到，去分成一个个的sheet页呢
     * <p>
     * 目前此方法还未写完
     */

    @Override
    public void exportData(String modelId, HttpServletResponse resp) {
        long starTime = System.currentTimeMillis();//执行此方法开始时间
        System.out.println("执行此方法开始时间：" + starTime);
        Map<String, String> mapCon = new HashMap<String, String>();
//			Map<String,String> parm=new HashMap<String,String>();
        List<AttrConfig> configLst = null;
        List<AttrConfig> jspAttrLst = new ArrayList<AttrConfig>();
        //获取当前登录用户的信息
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        try {
            //获取模型信息
            Model model = cacheUtil.getModel(modelId);
            mapCon.put("tableTable", model.getTableName());
            mapCon.put("userId", user.getUserId().toString());
//			        parm.put("modelId", modelId);
            OutputStream out = null;
            configLst = attrConfigDao.queryAttributesListPermision(mapCon);
            for (AttrConfig attrConfig : configLst) {
                //在新增页面展示，且不是编码格式
                jspAttrLst.add(attrConfig);
            }

            //第三种写法（刘晶写，从网上百度的一种导出大数据模板的方法）
            Workbook workbook = new SXSSFWorkbook(100); //创建新的Excel工作薄

            CellStyle style = workbook.createCellStyle();//单元格的样式
            DataFormat format = workbook.createDataFormat();//设置成文本格式
            style.setDataFormat(format.getFormat("@"));
            //    获取该表中所有的数据数据account
            int pageSize = 10000;//每个Excel的每个sheet页展示10000条数据
            long startSqlcount = System.currentTimeMillis();
            //获取该模型下，查询列表中展示的数据
            String sqlcount = "select count(*) from  " + model.getTableName();
            int dataNum = jdbcDao.executeSqlForCount(sqlcount);//返回来查询的结果
            long endSqlcount = System.currentTimeMillis();
            long times = endSqlcount - startSqlcount;//查询数据量用时
            System.out.println("查询数据count所用时间：" + times + "s");
            if (dataNum > 0) {
                int sheetNum = dataNum/pageSize;
                if (dataNum%pageSize == 0) {//如果余数大于0，则说明sheet页需要增加一个
                    sheetNum = dataNum/pageSize;
                } else {
                    sheetNum = dataNum/pageSize + 1;
                }
                //循环sheetNum分页查询数据然后导出数据
                for (int i = 1; i <= sheetNum; i++) {//循环sheet页，导出数据
                    long startsheetcount = System.currentTimeMillis();
                    Map<String, Object> param = new HashMap<>();//param参数
                    //系统列
                    StringBuilder sysCols = SystemAttributeFactory.getSystemColumnsBuilder();
                    String busiCols = cacheUtil.getQueryColumns(modelId);
                    String cols = sysCols.append(busiCols).toString();
                    param.put("columns", cols.subSequence(0, cols.length() - 1));
                    //循环将数据打印到EXCEL的sheet页面上
                    Sheet sheet = workbook.createSheet(model.getModelName() + i);    //创建本模型的工作表
                    Row row = sheet.createRow(0); //在索引0的位置创建行（最顶端的行）
                    sheet.setDefaultColumnWidth(30);//设置本sheet页,列的宽度

                    for (int j = 0; j < jspAttrLst.size(); j++) {
                        AttrConfig attr = jspAttrLst.get(j);
                        ExcelUtil.addSXSSWorkCell(sheet, row, attr.getAttrName(), j, style, null);
                    }
                    StringBuilder sort = new StringBuilder();
                    for (AttrConfig ac : jspAttrLst) {
                        if (ac.getIsOrder() == 1) {
                            sort.append(", ").append(ac.getAttrColumn());
                            if (ac.getOrderRule() == 1) {
                                sort.append(" asc");
                            } else if (ac.getOrderRule() == 2) {
                                sort.append(" desc");
                            }
                        }
                    }
                    sort.append(", to_number(id)  asc ").append(", ").append("version").append("  asc");
                    param.put("orderBy", sort.substring(1));
                    param.put("limit", pageSize);
                    param.put("pageNum", i);
                    param.put("state", 4);
                    param.put("tableName", model.getTableName());
                    PageHelper.startPage(i, pageSize);//分页  注释掉后就不会进行分页
                    List<Map<String, Object>> list = jspActionDao.queryList(param);
                    for (int m = 0; m < list.size(); m++) {
                        Row ContentRow = sheet.createRow(m + 1);
                        Map<String, Object> amap = list.get(m);
                        for (int j = 0; j < jspAttrLst.size(); j++) {
                            Cell cell = ContentRow.createCell(j);
                            cell.setCellType(Cell.CELL_TYPE_STRING);//设置单元格格式为文本
                            String colu = jspAttrLst.get(j).getAttrColumn().toLowerCase();
                            String name = (String) amap.get(colu.toLowerCase());
                            if (name == "null" || name == "") {
                                cell.setCellValue("null");
                            } else {
                                cell.setCellValue(name);
                            }
                        }
                    }
                    long endsheetcount = System.currentTimeMillis();
                    long sheetTime = endsheetcount - startsheetcount;
                    System.out.println("导出第" + i + "个sheet页用时" + sheetTime + "秒！");
                }
            } else {
                //循环将数据打印到EXCEL的sheet页面上
                Sheet sheet = workbook.createSheet(model.getModelName());    //创建本模型的工作表
                Row row = sheet.createRow(0); //在索引0的位置创建行（最顶端的行）
                sheet.setDefaultColumnWidth(30);//设置本sheet页,列的宽度
                ExcelUtil.addSXSSWorkCell(sheet, row, "该模板没有要导出来的数据！", 0, style, null);
//							    	 for (int j = 0; j < jspAttrLst.size(); j++) {
//									    	AttrConfig attr =jspAttrLst.get(j);
//										    ExcelUtil.addSXSSWorkCell(sheet,row,attr.getAttrName(),j,style,null);
//									}
            }
            out = resp.getOutputStream();
            ExcelUtil.setSXSSWorkResponseHeader(resp, model.getModelName());
            workbook.write(out);
            workbook.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();//执行此方法结束时间
        System.out.println("执行此方法结束时间：" + endTime);
        long mins = endTime - starTime;
        System.out.println("执行此方法用时：" + mins + "秒");
    }

    /**
     * <p>TODO</p>
     *
     * @param : @param param
     * @param : @return
     * @author : xiaoliu
     * @date :2018年1月2日下午12:51:47
     */
    @Override
    public PageInfo queryPopList(Map<String, Object> param) {
        PageInfo<List<Map>> pageInfo = null;
        try {
            Object mid = param.get("modelId");
            //模型ID
            String modelId = mid == null ? param.get("tableName").toString().substring(2) : mid.toString();
            //获取当前操作模型
            Model model = cacheUtil.getModel(modelId);
            //系统列
            StringBuilder sysCols = SystemAttributeFactory.getSystemColumnsBuilder();
            //业务属性
            //String busiCols = cacheUtil.getColumns(modelId);
            String busiCols = cacheUtil.getQueryColumns(modelId);
            String cols = sysCols.append(busiCols).toString();
            param.put("columns", cols.subSequence(0, cols.length() - 1));

            // 业务属性
            StringBuilder where = new StringBuilder();
            //StringBuilder flowColumn = new StringBuilder();
            Map<String, AttrConfig> ma = cacheUtil.getAttrMap(modelId);
            //获取实时的AttrConfig 不从缓存拿数据
            Map<String, AttrConfig> map = this.getNewAttrConfig(modelId);

            // ///////////////////////////////////////////////////////////////////////////////
            // 业务场景：A表关联B表一个字段，现在想查询B表的其他字段，下面的做法是写个视图，查询字段A.*+B表想要显示的字段
            // 然后在js中指定modelId:A;tableName：视图名字。
            // 下面方法中会将关联的B表字段赋值到查询列中
            // 注意：在新建的视图中，关联显示的字段如果不作为查询条件，名称可自定义，如果需要作为查询条件，则用"c_"开头+数字，例如：c_999，
            // 用数字是因为在spring-mybatis.xml文件中有定义"<plugin interceptor="com.liangtian.mdm.base.filter.CameHumpInterceptor"></plugin>"，下划线被去掉并转为驼峰写法，不符合下面代码中拼接查询条件的写法;

            List<Map<String, Object>> columnsList = new ArrayList<Map<String, Object>>();
            if ("V_".equals(param.get("tableName").toString().substring(0, 2).toUpperCase())) {
                columnsList = this.queryAlltabcolumns(param.get("tableName").toString());
                // 将视图中关联的字段加入查询字段中
                cols = this.addColumns(columnsList, cols);
                param.put("columns", cols.subSequence(0, cols.length() - 1));
                // ma = this.addma(ma,
                // sysCols.toString(),columnsList);//此方法会将视图中多加的字段加入ma,放入缓存，影响该模型其他地方的操作，比如新增
                map = this.addmap(map, sysCols.toString(), columnsList);
            }
            for (String key : param.keySet()) {
                if (key.startsWith(TableConst.COLUMNPREFIX.toLowerCase())) {
                    AttrConfig ac = new AttrConfig();
                    if ("V_".equals(param.get("tableName").toString().substring(0, 2).toUpperCase())) {
                        ac = map.get(key.toUpperCase());
                    } else {
                        if (key.endsWith(TableConst.FILTERSUFFIX)) {//如果是以"_FILTER"结尾的，说明在引用模型里设置的是级联条件
                            String columnCol = key.split(TableConst.FILTERSUFFIX)[0];
                            ac = ma.get(columnCol.toUpperCase());
                        } else {
                            ac = ma.get(key.toUpperCase());
                        }
                    }
                    if (ac != null) {
                        //如果这个属性列设置的是复选框
                        if ("checkBoxType".equals(ac.getAttrType())) {
                            where.append(" and ").append(key).append(" in (#{").append(key).append("}) ");
                        } else if ("popList".equals(ac.getAttrType())) {
                            //如果这个属性设置是弹出框，并且是级联设置的时候或者是下拉框(y因为只有下拉框和弹出框才可能会有
                            if (key.endsWith(TableConst.FILTERSUFFIX)) {//如果是以"_FILTER"结尾的，说明在引用模型里设置的是级联条件
                                String columnCol = key.split(TableConst.FILTERSUFFIX)[0];
                                where.append(" and ").append("t." + columnCol).append(" = '").append(param.get(key).toString()).append("' ");
                                if ("1".equals(ac.getModuleType())) {//本模型是弹出的关联设置
                                    where.append(" and ").append("t." + columnCol).append(" = '").append(param.get(key).toString()).append("' ");
                                } else {
                                    where.append(" and ").append("t." + columnCol).append(" like '%").append(param.get(key).toString()).append("%' ");
                                }
                            } else {
                                if ("1".equals(ac.getModuleType())) {//本模型是弹出的关联设置
                                    where.append(" and ").append("t." + key).append(" = #{").append(key).append("} ");
                                } else {
                                    where.append(" and ").append(key).append(" like '%'||#{").append(key).append("}||'%' ");
                                }
                            }
                        } else if ("selectList".equals(ac.getAttrType())) {
                            if ("1".equals(ac.getModuleType())) {//本模型是下拉关联设置
                                if (key.endsWith(TableConst.FILTERSUFFIX)) {
                                    String columnCol = key.split(TableConst.FILTERSUFFIX)[0];
                                    where.append(" and ").append(columnCol).append(" = #{").append(key).append("} ");
                                } else {
                                    where.append(" and ").append(key).append(" = #{").append(key).append("} ");
                                }

                            } else {
                                where.append(" and ").append(key).append(" like '%'||#{").append(key).append("}||'%' ");
                            }
                        } else {
                            where.append(" and ").append(key).append(" like '%'||#{").append(key).append("}||'%' ");
                        }
                    }
                }
            }
            param.put("where", where);
            StringBuilder sort = new StringBuilder();
            List<AttrConfig> acList = cacheUtil.getAttrList(modelId);
            for (AttrConfig ac : acList) {
                if (ac.getIsOrder() != null && ac.getIsOrder() == 1) {
                    sort.append(", ").append(ac.getAttrColumn());
                    if (ac.getOrderRule() != null && ac.getOrderRule() == 1) {
                        sort.append(" asc");
                    } else if (ac.getOrderRule() != null && ac.getOrderRule() == 2) {
                        sort.append(" desc");
                    }
                }
            }
            sort.append(", to_number(id)  asc ").append(", ").append("version").append("  asc");
            param.put("orderBy", sort.substring(1));

            // 当前用户参与审核数据查询条件
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            //默认查询条件
            String operType = String.valueOf(param.get("operType"));
            if ("apply".equals(operType)) {
                param.put("createrId", user.getUserId());
            }
            param.put("operType", operType);

            Object pNo = param.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());//页码
            } else {
                pageNum = 1;
            }
            //pageSize=0时不分页
            pageSize = Integer.parseInt(param.get("limit").toString());//每页条数
            PageHelper.startPage(pageNum, pageSize);//分页  注释掉后就不会进行分页
            List<Map<String, Object>> list = null;
            if (Flag.OPER_2.getCode().equals(operType)) {
                // 变更表
                param.put("modifyTableName", param.get("tableName") + TableConst.MODIFYSUFFIX);
                //Model model = cacheUtil.getModel(modelId);
                if (model.getIsSubtable() == 1) {
                    //从表没有流程相关数据
                    list = jspActionDao.querySubTableList(param);
                } else {
                    param.put("approveUserId", String.valueOf(user.getUserId()));
                    list = jspActionDao.queryApproveList(param);
                }
            } else if (Flag.OPER_1.getCode().equals(operType)
                    && !Flag.FORQUERY.getCode().equals(param.get(Flag.FORQUERY.getColumn()))) {
                list = jspActionDao.queryUpdateList(param);
            } else {
                list = jspActionDao.queryList(param);
            }

            pageInfo = new PageInfo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;

    }

    /**
     * <p>TODO 添加一个非物料模块冻结数据归档的功能</p>
     *
     * @param : @param cond
     * @param : @param list
     * @author : xiaoliu
     * @date :2018年4月17日下午12:51:06
     */

    @Override
    public void gdData(Map<String, Object> param) {
        this.insertGd(param);
        this.deleteGd(param);
    }


    /**
     * <p>TODO 此方法是后期添加的方法，主要是操作在归档界面对选择的数据进行归档的时候，将数据插入到归档表 </p>
     * <p>@param param
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2018年4月19日下午3:25:33
     */
    public boolean insertGd(Map<String, Object> param) {
        List<String> sqls = new ArrayList<String>();
        //获取到的是主表的表名 eg : T_1882_GD
        sqls = sqlUtil.genGdInsertSql(param, sqls);
        boolean ret = jdbcDao.executeSqlList(sqls, true);
        return ret;
    }


    /**
     * 归档删除
     */
    public int deleteGd(Map<String, Object> param) {
        //1.删除主表的数据    EG: T_1882_GD
        //首先得去获取主表的表名
        String tableName = String.valueOf(param.get("tableName"));
        if (tableName.endsWith(TableConst.GDSUFFIX)) {//判断表结尾是不是 “_GD”结尾的表名
            tableName = tableName.substring(0, tableName.lastIndexOf("_"));//获取主表的数据
        }
        String modelId = tableName.split("_")[1];
        Map gdmapcon = new HashMap();
        gdmapcon.put("tableName", tableName);
        gdmapcon.put("modelId", modelId);
        gdmapcon.put("ids", param.get("ids"));
        int ret = jspActionDao.deleteByPk(gdmapcon);


        //2.删除变更表里的数据
        jspActionDao.deleteByOrgPk(gdmapcon);

        //3.删除从表里的数据
//			List<Model> subModels = modelDao.isHasSub(tableName.split("_")[1]);
//			if(!subModels.isEmpty()){
//				for(Model sub : subModels){
//					String table = sub.getTableName();
//					//变更主表【对应】变更从表
//					if(tableName.endsWith(TableConst.MODIFYSUFFIX)){
//						table = table + TableConst.MODIFYSUFFIX;
//					}
//					Map<String, Object> subParam = genSubProcessParam(table, param.get("ids").toString());
//					if (subParam != null) {
//						this.delete(subParam);
//					}
//				}
//			}

        //4.删除多视图表里的数据
        Model model = cacheUtil.getModel(tableName.split("_")[1]);
        if (model.getIsMoreView() == 1) {//是多视图数据
            String ids = param.get("ids").toString();
            String[] idLst = ids.split(",");
            for (int i = 0; i < idLst.length; i++) {
                Map map = new HashMap();
                map.put("modelId", tableName.split("_")[1]);
                map.put("dataId", idLst[i]);
                this.deleteDataFlow(map);
            }
        }

        return ret;
    }
}